Reputation: 6334
I am running into an issue where if I try to close the entity manager, and then open open it again, my sqlite database is locking:
Caused by: java.sql.SQLException: database is locked
at org.sqlite.DB.throwex(DB.java:370)
at org.sqlite.DB.exec(DB.java:76)
But if I just leave the entitymanager open, I don't see the error. So my question is, do I really need to close it? What if this is the only application that will be using this database, does that make a difference in whether or not it needs to be closed?
Here are the 2 methods I created. I was calling initTransaction(), then persisting my objects and committing, and then calling endTransaction(). The error would occur the second time I tried to do this, on 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;
}
Upvotes: 1
Views: 787
Reputation: 18379
Yes, you need to close the EntityManager. The EntityManagerFactory should not normally be closed, it should be held in a static variable as a singleton.
Upvotes: 1