我正在学习JPA。在下面的代码中,我尝试保留Point
,然后列出Points
进行检查,结果发现它尚未保存。为什么呢?
谢谢!
PersistenceProvider provider = new PersistenceProvider();
EntityManagerFactory emf = provider.createEntityManagerFactory("sample", null);
EntityManager em = emf.createEntityManager();
// DROP TABLE POINT
// CREATE TABLE POINT (ID BIGINT NOT NULL, X DOUBLE, Y DOUBLE, PRIMARY KEY (ID))
// DELETE FROM SEQUENCE WHERE SEQ_NAME = 'SEQ_GEN'
// SELECT * FROM SEQUENCE WHERE SEQ_NAME = 'SEQ_GEN'
// INSERT INTO SEQUENCE(SEQ_NAME, SEQ_COUNT) values ('SEQ_GEN', 0)
Point p = new Point(1, 1);
em.persist(p);
// UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?
// bind => [2 parameters bound]
// SELECT SEQ_COUNT FROM SEQUENCE WHERE SEQ_NAME = ?
// bind => [1 parameter bound]
em.close();
EntityManager em2 = emf.createEntityManager();
Query query = em2.createQuery("select p from Point p");
List list = query.getResultList();
// SELECT ID, X, Y FROM POINT
System.out.println("Found objects: " + list.size());
// Found objects: 0
for (Object elt: list){
System.out.println(elt);
}
答案 0 :(得分:2)
由于那里没有交易,因此没有提交任何内容。
一些JPA提供商将允许“非事务性”写入(您正在尝试执行此操作,例如DataNucleus JPA),但许多人不会,因此您需要执行
em.getTransaction().begin();
... (persist, merge, remove calls)
em.getTransaction().commit();
如果您需要独立于供应商的持久性代码