我正在尝试将Hibernate集成到我的Spring项目中,用户可以在其中注册,登录,然后他们可以创建配方。我建立的关系意味着食谱必须有一个用户。因此,在我的RecipeDao中,配方通过principal.getName()获取用户名,然后将配方保存到数据库中。食谱保存到我的食谱表中,然而,我得到了这个错误。
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is javax.validation.ConstraintViolationException: Validation failed for classes [com.finalspringproject.dao.User] during update time for groups [com.finalspringproject.dao.PersistenceValidationGroup, ]
List of constraint violations:[
ConstraintViolationImpl{interpolatedMessage='may not be empty', propertyPath=password, rootBeanClass=class com.finalspringproject.dao.User, messageTemplate='{org.hibernate.validator.constraints.NotBlank.message}'}
ConstraintViolationImpl{interpolatedMessage='may not be empty', propertyPath=email, rootBeanClass=class com.finalspringproject.dao.User, messageTemplate='{org.hibernate.validator.constraints.NotBlank.message}'}
]
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:948)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:146)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:183)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
root cause
javax.validation.ConstraintViolationException: Validation failed for classes [com.finalspringproject.dao.User] during update time for groups [com.finalspringproject.dao.PersistenceValidationGroup, ]
List of constraint violations:[
ConstraintViolationImpl{interpolatedMessage='may not be empty', propertyPath=password, rootBeanClass=class com.finalspringproject.dao.User, messageTemplate='{org.hibernate.validator.constraints.NotBlank.message}'}
ConstraintViolationImpl{interpolatedMessage='may not be empty', propertyPath=email, rootBeanClass=class com.finalspringproject.dao.User, messageTemplate='{org.hibernate.validator.constraints.NotBlank.message}'}
]
org.hibernate.cfg.beanvalidation.BeanValidationEventListener.validate(BeanValidationEventListener.java:161)
org.hibernate.cfg.beanvalidation.BeanValidationEventListener.onPreUpdate(BeanValidationEventListener.java:102)
org.hibernate.action.EntityUpdateAction.preUpdate(EntityUpdateAction.java:237)
org.hibernate.action.EntityUpdateAction.execute(EntityUpdateAction.java:86)
org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)
org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:265)
org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:185)
org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
org.springframework.orm.hibernate3.SpringSessionSynchronization.beforeCommit(SpringSessionSynchronization.java:145)
org.springframework.transaction.support.TransactionSynchronizationUtils.triggerBeforeCommit(TransactionSynchronizationUtils.java:95)
org.springframework.transaction.support.AbstractPlatformTransactionManager.triggerBeforeCommit(AbstractPlatformTransactionManager.java:925)
org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:738)
org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:724)
org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:475)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:270)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:631)
com.finalspringproject.dao.RecipeDAO$$EnhancerByCGLIB$$40f9f16.saveOrUpdate(<generated>)
com.finalspringproject.service.RecipeService.saveOrUpdate(RecipeService.java:71)
com.finalspringproject.service.RecipeService$$FastClassByCGLIB$$96c55643.invoke(<generated>)
org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:627)
com.finalspringproject.service.RecipeService$$EnhancerByCGLIB$$20d5df6c.saveOrUpdate(<generated>)
com.finalspringproject.controllers.RecipeController.doCreate(RecipeController.java:90)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:146)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:183)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
这是我的食谱类。
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
@Entity
@Table(name="recipe")
public class Recipe {
@Id
private int id;
@Size(min = 5, max = 100,groups={FormValidationGroup.class,PersistenceValidationGroup.class})
private String titleParse;
@Size(min = 5, max = 200groups = {FormValidationGroup.class, PersistenceValidationGroup.class })
private String descriptionParse;
private String imageURLParse;
@NotNull(groups = {FormValidationGroup.class, PersistenceValidationGroup.class })
private String ratingParse;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name="username")
private User user;
public Recipe() {
this.user= new User();
}
public Recipe(User user, String titleParse, String descriptionParse, String imageURLParse, String ratingParse) {
this.user = user;
this.titleParse = titleParse;
this.descriptionParse = descriptionParse;
this.imageURLParse = imageURLParse;
this.ratingParse = ratingParse;
}
public Recipe(int id, User user, String titleParse, String descriptionParse, String imageURLParse,
String ratingParse) {
this.id = id;
this.user = user;
this.titleParse = titleParse;
this.descriptionParse = descriptionParse;
this.imageURLParse = imageURLParse;
this.ratingParse = ratingParse;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitleParse() {
return titleParse;
}
public void setTitleParse(String titleParse) {
this.titleParse = titleParse;
}
public String getDescriptionParse() {
return descriptionParse;
}
public void setDescriptionParse(String descriptionParse) {
this.descriptionParse = descriptionParse;
}
public String getImageURLParse() {
return imageURLParse;
}
public void setImageURLParse(String imageURLParse) {
this.imageURLParse = imageURLParse;
}
public String getRatingParse() {
return ratingParse;
}
public void setRatingParse(String ratingParse) {
this.ratingParse = ratingParse;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getUsername() {
return user.getUsername();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((descriptionParse == null) ? 0 : descriptionParse.hashCode());
result = prime * result + ((imageURLParse == null) ? 0 : imageURLParse.hashCode());
result = prime * result + ((ratingParse == null) ? 0 : ratingParse.hashCode());
result = prime * result + ((titleParse == null) ? 0 : titleParse.hashCode());
result = prime * result + ((user == null) ? 0 : user.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Recipe other = (Recipe) obj;
if (descriptionParse == null) {
if (other.descriptionParse != null)
return false;
} else if (!descriptionParse.equals(other.descriptionParse))
return false;
if (imageURLParse == null) {
if (other.imageURLParse != null)
return false;
} else if (!imageURLParse.equals(other.imageURLParse))
return false;
if (ratingParse == null) {
if (other.ratingParse != null)
return false;
} else if (!ratingParse.equals(other.ratingParse))
return false;
if (titleParse == null) {
if (other.titleParse != null)
return false;
} else if (!titleParse.equals(other.titleParse))
return false;
if (user == null) {
if (other.user != null)
return false;
} else if (!user.equals(other.user))
return false;
return true;
}
}
这是我的RecipeServiceClass。
@Service("recipeService")
public class RecipeService {
private RecipeDAO recipeDao;
public RecipeService() {
}
public List<Recipe> getCurrent() {
System.out.println("In the Current Service");
return recipeDao.getRecipe();
}
public List<Recipe> getCurrent(String username) {
System.out.println("In the Current Service with username");
return recipeDao.getRecipe(username);
}
@Autowired
public void setRecipeDao(RecipeDAO recipeDao) {
this.recipeDao = recipeDao;
}
@Secured({"ROLE_USER","ROLE_ADMIN"})
public void create(Recipe recipe){
recipeDao.saveOrUpdate(recipe);
}
public boolean hadRecipe(String name) {
if(name ==null) {
return false;
}
List<Recipe> recipes = recipeDao.getRecipe(name);
if(recipes.size()==0){
return false;
}
return true;
}
public Recipe getRecipe(String username) {
if(username==null){
return null;
}
List<Recipe> recipes = recipeDao.getRecipe(username);
if(recipes.size()==0){
return null;
}
return recipes.get(0);
}
public void saveOrUpdate(Recipe recipe) {
System.out.println("in the save or update/ Service");
recipeDao.saveOrUpdate(recipe);
}
public void delete(int id) {
recipeDao.delete(id);
}
}
这是我的RecipeDao课程。
@Transactional
@Repository
@Component("recipeDao")
public class RecipeDAO {
@Autowired
private SessionFactory sessionFactory;
public Session session() {
return sessionFactory.getCurrentSession();
}
@SuppressWarnings("unchecked")
public List<Recipe> getRecipe() {
System.out.println("In the get recipe, Dao");
Criteria crit = session().createCriteria(Recipe.class);
crit.createAlias("user", "u").add(Restrictions.eq("u.enabled", true));
System.out.println("In the get recipe, Dao2");
return crit.list();
}
@SuppressWarnings("unchecked")
public List<Recipe> getRecipe(String username) {
System.out.println("In the get recipe, Dao with username");
Criteria crit = session().createCriteria(Recipe.class);
crit.createAlias("user", "u");
crit.add(Restrictions.eq("u.enabled", true));
crit.add(Restrictions.eq("u.username", username));
System.out.println("In the get recipe, Dao with username2");
return crit.list();
}
public void saveOrUpdate(Recipe recipe) {
System.out.println("in the save session " + recipe.toString());
session().saveOrUpdate(recipe);
}
public boolean delete(int id) {
Query query = session().createQuery("delete from Recipe where id=:id");
query.setLong("id", id);
return query.executeUpdate() == 1;
}
public Recipe getRecipe(int id) {
Criteria crit = session().createCriteria(Recipe.class);
crit.createAlias("user", "u");
crit.add(Restrictions.eq("u.enabled", true));
crit.add(Restrictions.idEq(id));
return (Recipe) crit.uniqueResult();
}
}
这是我的用户类。
@Entity
@Table(name = "user")
public class User {
@Id
@NotBlank(groups = {FormValidationGroup.class, PersistenceValidationGroup.class })
@Size(min = 5, max = 20, groups = {FormValidationGroup.class, PersistenceValidationGroup.class })
private String username;
@NotBlank(groups = {FormValidationGroup.class, PersistenceValidationGroup.class })
@Email(message = "This is an invalid email address", groups = {FormValidationGroup.class,PersistenceValidationGroup.class })
private String email;
@NotBlank(groups = {FormValidationGroup.class, PersistenceValidationGroup.class })
@Size(min = 3, max = 15, groups = {FormValidationGroup.class })
private String password;
private boolean enabled = false;
private String authority;
public User() {
}
public User(String username, String email, String password, boolean enabled, String authority,
List<Recipe> recipe) {
super();
this.username = username;
this.email = email;
this.password = password;
this.enabled = enabled;
this.authority = authority;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getAuthority() {
return authority;
}
public void setAuthority(String authority) {
this.authority = authority;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((authority == null) ? 0 : authority.hashCode());
result = prime * result + ((email == null) ? 0 : email.hashCode());
result = prime * result + (enabled ? 1231 : 1237);
result = prime * result + ((password == null) ? 0 : password.hashCode());
result = prime * result + ((username == null) ? 0 : username.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (authority == null) {
if (other.authority != null)
return false;
} else if (!authority.equals(other.authority))
return false;
if (email == null) {
if (other.email != null)
return false;
} else if (!email.equals(other.email))
return false;
if (enabled != other.enabled)
return false;
if (password == null) {
if (other.password != null)
return false;
} else if (!password.equals(other.password))
return false;
if (username == null) {
if (other.username != null)
return false;
} else if (!username.equals(other.username))
return false;
return true;
}
@Override
public String toString() {
return "User [ username=" + username + ", email=" + email + ", enabled=" + enabled
+ ", authority=" + authority + "]";
}
}
这是我的食谱控制器。
@Controller
public class RecipeController {
private RecipeService recipeService;
@Autowired
public void setRecipeService(RecipeService recipeService) {
this.recipeService = recipeService;
}
@RequestMapping("/allrecipes")
public String showRecipe(Model model) {
List<Recipe> recipe = recipeService.getCurrent();
model.addAttribute("recipe", recipe);
return "allrecipes";
}
@RequestMapping("/createrecipe")
public String createRecipe(Model model, Principal principal) {
System.out.println("in the create recipe");
Recipe recipe = null;
if (principal != null) {
String username = principal.getName();
System.out.println("in the create recipe, principal not null");
recipe = recipeService.getRecipe(username);
}
if (recipe == null) {
System.out.println("in the create recipe,new recipe");
recipe = new Recipe();
}
System.out.println("in the create recipe: " + recipe);
model.addAttribute("recipe",recipe);// command name in the form,
// must have an recipe
// object
System.out.println("in the create recipe:2 " + recipe);
return "createrecipe";
}
@RequestMapping(value = "/docreate", method = RequestMethod.POST)
public String doCreate(Model model, @Validated(value=FormValidationGroup.class) Recipe recipe,
BindingResult result, Principal principal,
@RequestParam(value = "delete", required = false) String delete) {
if (result.hasErrors()) {
return "createrecipe";
}
if (delete == null) {
String username = principal.getName();
recipe.getUser().setUsername(username);
System.out.println("in the docreate");
recipeService.saveOrUpdate(recipe);
return "recipecreated";
} else {
recipeService.delete(recipe.getId());
return "recipedeleted";
}
}
}
我只是不明白为什么它会将配方添加到表中但它会引发错误。感谢无论谁能提供帮助。
答案 0 :(得分:0)
可以回答我自己的问题吗?我通过删除
来修复它groups = {FormValidationGroup.class, PersistenceValidationGroup.class}
来自每个用户属性,它的作品非常适合于食谱类,因此我不确定为什么会发生这种情况。但删除它确实解决了我的问题