JPA-如何在构造函数中获取自动生成的id?
我想要实现的是获取自动生成的ID,将其散列并将其保存到类中的其他字段中,但在通过构造函数ID创建对象的阶段尚未生成。任何解决方法的想法?
@Entity
public class MyClass {
@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.AUTO)
Long id;
String hashID;
MyClass(){
this.hashID = Utils.hashID(id);
}
//setters and getters
}
```
回答
我能想到的一种方法是您可以使用实体生命周期回调事件,例如@PostLoad在持久性上下文中加载实体时调用的事件,并从 id 初始化散列字段。
例如
@Entity
public class MyClass {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
Long id;
String hashID;
@PostLoad
public void postLoad() {
// Here id is initialized
this.hashID = Utils.hashID(id);
}
}
- 我认为这取决于你在回调中做了什么,如果它没有做一些性能密集型的事情,那么一切都应该没问题。