我目前使用Hibernate作为ORM开发Spring应用程序。我知道只要实体被持久化或加载,Hibernate默认使用JSR-303 Bean Validation。由于此应用程序支持草稿(我希望在持久化后执行验证),我不得不将其添加到persistence.xml:
<validation-mode>NONE</validation-mode>
for hibernate不执行这些验证。问题是,当我尝试在实体上手动执行bean验证时(当草稿成为文档时),hibernate尚未加载的元素(验证时PersistentBag的实例)未经验证,这里是代码示例
控制器方法代码:
@RequestMapping(value = "/entity/{entity_id}", method = RequestMethod.POST)
public String completeEntity(@PathVariable("entity_id") Long entity_id)
{
//myEntityService was autowired in the controller
MyEntity myEntity = myEntityService.findById(entity_id);
//Here comes the bean validation
DataBinder binder = new DataBinder(myEntity);
//validator was also autowired
binder.setValidator(validator);
binder.validate();
BindingResult result = binder.getBindingResult();
if (result.hasErrors()) {
//handleErrors
}
//continue doing stuff, marking the entity as 'not draft' and persisting it...
}
模型实体代码:
@Entity
@Table(name = "myEntity")
public class MyEntity{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank
String foo;
// bi-directional one-to-many association to Bar
//Note the valid annotation, as i want all related Bar's to be validated
//when a MyEntity is validated
@Valid
@OneToMany(mappedBy = "myEntity")
private List<Bar> bars;
//Getters and Setters...
}
@Entity
@Table(name = "bar")
public class Bar{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank
String barFoo;
// bi-directional many-to-one association to MyEntity
@ManyToOne
private MyEntity myEntity;
//Getters and Setters...
}
我想知道如何传播bean验证,以便每当验证MyEntity实例时,所有关联的Bar都会得到验证,而不必在验证之前强制加载这些实体。 / p>
答案 0 :(得分:0)
您可以实现自定义traversable resolver并配置Bean验证以使用此验证。
默认实现确保没有从数据库加载任何对象(假设它们在上次写入时已成功验证),但您可以根据您的要求覆盖特定关联。