英文:
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事务之后执行。
在您的情况下,您可以:
- 在
persist
方法之后手动设置code
,然后发起另一个保存顾客的请求,其中包括这个code
。 - 您可以保留
@PostPersist
注解,但在这种情况下,您还需要另一个保存请求。 - 如果您正在使用
自定义生成器
,您可以在保存之前获取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:
- Set
code
manualy afterpersist
method and make another request for saving of customer with thiscode
- You can leave the
@PostPersist
annotation, but in this case you also need another save request - If you are using
custom generator
, you could getid
before saving (https://stackoverflow.com/questions/12742826/how-do-i-know-the-id-before-saving-an-object-in-jpa)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论