JPA持久性上下文什么时候结束?

时间:2017-10-20 04:24:42

标签: java hibernate jpa

通过Java Persistence Entity Operations ATM阅读,其中包含以下声明:

  

JPA通过在序列化或持久化上下文结束时自动分离实体来提供对此模式的支持。

持久性上下文何时结束?是在每次交易结束时吗?

1 个答案:

答案 0 :(得分:1)

在调用EntityManager.close()时,持久性上下文结束。 Here's an example

从问题中提供的链接中获取的另一个例子:

MagazineId mi = new MagazineId();
mi.isbn = "1B78-YU9L";
mi.title = "JavaWorld";

// updates should always be made within transactions; note that
// there is no code explicitly linking the magazine or company
// with the transaction; JPA automatically tracks all changes
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
Magazine mag = em.find(Magazine.class, mi);
mag.setPrice(5.99);
Company pub = mag.getPublisher();
pub.setRevenue(1750000D);
em.getTransaction().commit();

// or we could continue using the EntityManager...
em.close();