Does @PreUpdate always run when @PrePersist runs?

梦想的初衷 提交于 2021-01-27 20:23:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!