在PostPersist事件方法中更新JPA实体。

huangapple go评论75阅读模式
英文:

Update the JPA entity in PostPersist event method

问题

我想在@PostPersist方法中更新实体,以便获取生成的ID并将其放入同一表中的另一列中:

@PostPersist
public void postPersist(Customer customer) {
   customer.setCode("Code_" + customer.getId());
}

这个更新不会在数据库中持久化。那么,我应该怎么做才能使用附加到生成的ID的字符串“Code_”来更新我的实体呢?

英文:

I want to update the entity in @PostPersist method in order to get the generated ID and put it in another column in the same table :

@PostPersist
public void postPersist(Customer customer) {
   customer.setCode("Code_" + customer.getId);
}

This update is not persisted in the DataBase. So what I should do to update my entity using the String "Code_" appended to the generated Id.

答案1

得分: 1

@PostPersist@PrePersist是回调方法。它们会在JPA事务之后执行。
在您的情况下,您可以:

  1. persist方法之后手动设置code,然后发起另一个保存顾客的请求,其中包括这个code
  2. 您可以保留@PostPersist注解,但在这种情况下,您还需要另一个保存请求。
  3. 如果您正在使用自定义生成器,您可以在保存之前获取id(https://stackoverflow.com/questions/12742826/how-do-i-know-the-id-before-saving-an-object-in-jpa)

代码示例

英文:

@PostPersit and @PrePersist are callback methods. They are executed after the JPA transaction.
In your case you could:

  1. Set code manualy after persist method and make another request for saving of customer with this code
  2. You can leave the @PostPersist annotation, but in this case you also need another save request
  3. If you are using custom generator, you could get id before saving (https://stackoverflow.com/questions/12742826/how-do-i-know-the-id-before-saving-an-object-in-jpa)

Code example

huangapple
  • 本文由 发表于 2020年10月23日 01:57:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/64487971.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定