I have a POJO called Order
as follows:
public class Order {
@Id
@GeneratedValue
@Column(name="id")
protected int id;
@NotNull
@Future
protected Date desiredProcessingDate;
protected Date actualProcessingDate;
}
As you can see, desiredProcessingDate must be specified and it must be in the future. A user will submit a new order through a form and specify a desiredProcessingDate
, which is being validated as expected. The order is then persisted to the database via sessionFactory.getCurrentSession().persist(order);
At a later date a scheduled service will retrieve the order from the database, process it and stamp the actualProcessingDate
with the current timestamp.
However, when this service calls sessionFactory.getCurrentSession().merge(order);
the validation kicks in again and fails because desiredProcessingDate
is now in the past.
It seems like what I need to do is to tell the merge(order)
operation not to validate, but am unsure how to do this.
If this is not possible then it seems like to only way around it is to write a class-level custom validator which only checks that desiredProcessingDate
is in the future if actualProcessingDate == null
, which seems overly complex for what seems like a simple requirement. Any pointers would be appreciated.
The validation behaviour in JPA can be configured using the the properties javax.persistence.validation.group.pre-persist
, javax.persistence.validation.group.pre-update
and javax.persistence.validation.group.pre-remove
. The values for these properties is a comma separated list of the fully qualified classnames of the validation groups to target for each of the given JPA life cycle event, eg:
<property name="javax.persistence.validation.group.pre-persist" value="javax.validation.groups.Default,com.acme.PrePersist"/>
<property name="javax.persistence.validation.group.pre-update" value="javax.validation.groups.Default"/>
As a solution to your problem is to add the @Future
constraint to a "PrePersist" group in which case it only gets validated on persist and not on update.