我什么时候才能可靠地知道新创建实体的 id
字段用 @GenerateValue
注释已由持久性提供程序
设置?
JPA 规范对此并不是很具体。我见过类似的问题,但他们得到不同且令人困惑的答案。我知道一旦事务提交,id就已经设置了,但是如果事务仍在运行并且我需要id怎么办?
如何可靠地获取它?
最佳答案
也许你可以试试这个。调用flush ()方法可以将未保存的数据推送到数据库。
// Use persist in a transaction
// It doesn't guarantee that the identifier value will be assigned to the persistent instance immediately,
// the assignment might happen at flush time so call the flush method.
public T persist(T obj) {
entityManager.persist(obj);
entityManager.flush();
return obj;
}
关于java - 什么时候设置带有 @GenerateValue 注解的 Id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44459977/