Spring MVC with Hibernate Validator对数据库字段是必需的,但在应用程序中不是

时间:2013-12-25 06:32:03

标签: spring hibernate spring-mvc hibernate-validator

验证中BindingResult hasErrors()出现问题。 我有这段代码:

@RequestMapping(value = "/entity", params = "form", method = RequestMethod.POST)
  public String submit(@Valid @ModelAttribute Entity entity, BindingResult result) {
  Authentication auth = SecurityContextHolder.getContext().getAuthentication();
  entity.setCreatedBy(auth.getName());
  if (result.hasErrors()) {
     //Here the error of createdBy is null
     return "entity/new";
  } else {
     entityService.save(entity);
     return "redirect:/entity/list";
  }
}

实体类:

@Entity
@Table(name = "TABLE_X")
public class Entity implements Serializable {
   private static final long serialVersionUID = 1L;
   @Id
   @NotNull
   @Column(name = "primary_key")
   private String primaryKey;
   @NotNull
   @Column(name = "created_by")
   private String createdBy;
   //getters and setter
}

我需要在控制器中设置createdBy的值,但在视图中始终显示“可能不为空”。 请帮忙。

Spring MVC 4 Hibernate Validator 5 数据库Oracle 11g

1 个答案:

答案 0 :(得分:2)

在Spring MVC调用entity方法之前验证了您的submit()对象。 result对象同时创建。这一行:

entity.setCreatedBy(auth.getName());

result.hasErrors()的结果完全没有影响。