1
我遇到了一个问题:如果我试图关闭实体管理器,然后打开开了一遍,我的SQLite数据库被锁定:值关闭的JPA EntityManager,对保持它打开
Caused by: java.sql.SQLException: database is locked
at org.sqlite.DB.throwex(DB.java:370)
at org.sqlite.DB.exec(DB.java:76)
但如果我只是离开entitymanager打开,我不会看到错误。所以我的问题是,我真的需要关闭它吗?如果这是将使用此数据库的唯一应用程序,那么它是否会影响它是否需要关闭?
以下是我创建的两种方法。我正在调用initTransaction(),然后坚持我的对象并提交,然后调用endTransaction()。第二次尝试在tx.commit()上执行此操作时会发生错误。
private EntityManagerFactory emf;
private EntityManager em;
private EntityTransaction tx;
//in my Java backing bean, multiple methods
initTransaction();
em.persist(someObject);
tx.commit(); //Exception thrown here, but OK first time thru
endTransaction();
private synchronized void initTransaction() {
if (emf == null || !emf.isOpen()) { emf = Persistence.createEntityManagerFactory("persistenceUnitSqlite"); };
if (em == null || !em.isOpen()) { em = emf.createEntityManager(); }
tx = em.getTransaction();
if (!tx.isActive()) { tx.begin(); }
}
private synchronized void endTransaction() {
if (em != null) { em.clear(); em.close(); }
if (emf != null) { emf.close(); }
tx = null;
}
感谢您的回答。我已经做了一些更深入的研究,现在我明白工厂对象应该只创建一次。从JBoss文档:'EntityManagerFactory是一个代价高昂的线程安全对象,旨在被所有应用程序线程共享。它通常在应用程序启动时创建一次。“ – MattC
我也知道EntityManager是数据的“缓存”,但我仍然不明白你什么时候应该关闭它或保持打开状态。 – MattC