Antonio has written a nice article on how to use Bean Validation and Hibernate Validator 4.0 in JPA 1.0 and Hibernate 3.3 (by retrofitting what's happening automatically in JPA 2.0). He asked an interesting question at the end of his post.

While he understands the benefit of JPA 2.0 calling Bean Validation on entity creation or update, he is wondering about the use case driving the ability to trigger validation when an entity is removed.

The feature was not in initially but a user came with an interesting use case during the review process:

I want to be sure an order is paid before deleting it from the system. If it's not paid, I am not legally allowed to remove it.

Here is the solution:

@Entity class Order {
   @Id @GeneratedValue public Integer getId() { return id; }
   public void setId(Integer id) { = id; }
   private Integer id;

   @AssertTrue(groups=LegallyRemovable.class) public boolean isPaid() { return paid; }
   public void setPaid(boolean paid) { this.paid = paid; }
   private boolean paid;


<persistence-unit name="OrderManagement">
    <property name=""></property>

The application will likely do something like that at the service layer:

if ( validator.validate(order, LegallyRemovable.class).size() > 0 ) {
  throw BusinessException(...);

But if for some reason a developper forgets to do it or an order is deleted by cascade, the JPA 2 validation layer will be here to save you.

Note that by default, no group is validated when entities are removed which makes sense for 99% of the use cases out there.

Back to top