该实体有一个通用 ID 生成器,
实体
@Entity
public class Customer {
@Id
@GenericGenerator(name = "seq_id", strategy = "com.yoncabt.abys.core.listener.CustomGenerator", parameters = { @Parameter(name = "sequence", value = "II_FIRM_DOC_PRM_SEQ") })
@GeneratedValue(generator = "seq_id")
private Long id;
private String name;
private String email;
private String token;
private string filepath;
private String value;
@PrePersist
private void prePersistFunction(){
log.info("PrePersist method called");
filepath = id+".txt";
write value to this file (filetpath)
value = null;
}
...
//getters
//equals and hashcode
}
在这种情况下,文件路径值将 id 设为 null。我怎样才能在 preperists 中获取 id 的值,因为这是一个自定义的通用生成器,而不是数据库?
谢谢
最佳答案
你不能在 pre persist 中做到这一点。 @PrePersist
在为新实体调用persist 之前执行带注释的函数。此时尚未生成 ID 所以你不能基于它组成一个字段。
您可以在自定义生成器中执行此操作。您的自定义生成器应该有一个 generate
计算并返回实体 ID 的方法。您还可以访问被持久化的实体,除此之外,您还可以设置组合字段:
@Override
public Serializable generate(SharedSessionContractImplementor session, Object obj) {
long id = // Calculate new id
// obj is the entity being persisted whose identifier will be set with calculated id
// We can set other fields as well
Customer customer = (Customer) obj;
customer.setFilepath(id+".txt");
return id;
}
关于java - 在提交之前在预持久方法中获取 JPA 中生成的 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66029355/