I'm currently developing an application with Spring using Hibernate as ORM. I know that Hibernate by default uses JSR-303 Bean Validation whenever an entity is persisted or loaded. As this application supports drafts (and i want validations to be performed after persisting) i had to add this to persistence.xml:
<validation-mode>NONE</validation-mode>
for hibernate not to perform these validation. The problem is that when i try to manually perform bean validation on an entity (when a draft becomes a document) the element that are not yet loaded by hibernate (instances of PersistentBag by the time of validation) are not validated, here is a code example.
Controller method code:
@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...
}
Model entities code:
@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...
}
I'd like to know how can i propagate bean validation so that whenever a MyEntity instance is validated, all associated Bar's are validated as well, without having to forcefully load these entities right before validation.