问题
I have an Entity like below:
@Entity
public class Order {
@Id
private String orderId;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "created_at", nullable = false)
private Date created;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "updated_at", nullable = false)
private Date updated;
@PrePersist
protected void onCreate() {
this.created = new Date();
this.updated = this.created;
}
@PreUpdate
protected void onUpdate() {
this.updated = new Date();
}
}
I have to find all the orders that have created or updated date within a particular date range. For that I have below method defined in my repository:
public interface OrderRepository extends PagingAndSortingRepository<Order, String>,
QuerydslPredicateExecutor<Order> {
public Page<Order> findByCreatedBetweenOrUpdatedBetween(Date startCreatedDate,
Date endCreatedDate, Date startUpdatedDate, Date endUptedDate, Pageable pageRequest);
}
My question is, can I just check for Updated_date
for this instead of both created and updated date like below?
public Page<Order> findByUpdatedBetween(Date startUpdatedDate, Date endUptedDate, Pageable pageRequest);
What I observed is updated_date
is updated at the time a row in inserted with the same value as created_date
. Is there a chance I would miss any of the records if I just check updated_date for the date range provided.
回答1:
No, @PreUpdate
callback method does not always run when @PrePersist
callback method is executed. @PrePersist
is executed before persist operation (direct or cascaded) and @PreUpdate
before database update.
In JPA 2.1 specification (3.5.3 Semantics of the Life Cycle Callback Methods for Entities) this is told with following words:
The PrePersist and PreRemove callback methods are invoked for a given entity before the respective EntityManager persist and remove operations for that entity are executed.
...
The PreUpdate and PostUpdate callbacks occur before and after the database update operations to entity data respectively.
来源:https://stackoverflow.com/questions/54231332/does-preupdate-always-run-when-prepersist-runs