何时使用@GeneratedValue设置注释的Id?

时间:2017-06-09 14:10:20

标签: java jpa

我什么时候能够可靠地知道id设置了新创建的实体@GeneratedValue注释的persistence provider字段?

JPA规范对此并不十分具体。我见过类似的问题,但是他们的答案却各不相同。我知道一旦提交了事务,id就已经设置了,但是如果事务仍然在运行并且我需要id呢?

我怎样才能可靠地获得它?

1 个答案:

答案 0 :(得分:0)

可能你可以试试这个。调用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;
}
相关问题