Hi to everyone,
I've a little question. I work with Hibernate JPA in an simple Java Application, which runs in the JVM, not in some Application Server or something.
This application is a client server application where communication is done by RMI. The Database is at the servers machine, if you want to know
Sometimes I get an IllegalStateException with that the message that the EntityManager is closed when a client calls a remote method
Code:
java.lang.IllegalStateException: EntityManager is closed
at org.hibernate.ejb.EntityManagerImpl.getSession(EntityManagerImpl.java:66)
at org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:93)
at de.jhomuth.itbos.server.persistence.UserPersistenceFacade.getAllUsers(UserPersistenceFacade.java:166)
....
....
When I persist a user for example I will call the entitymanager.close() method. This method will called at other locations too, here only an example
Code:
/**
* This method adds a Service to the db
* @param category
*/
public void persist(User user) {
em.getTransaction().begin();
try {
em.persist(user);
em.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
em.getTransaction().rollback();
} finally {
em.close(); //CLOSE CALL HERE
}
}
When I try to create a query with the entitymanger, after the close method was called, I get the provided exception
Code:
public User getUserByUid(String uid) {
Query q = em.createQuery("SELECT user FROM User user where user.uid=:uid"); //EXCEPTION OCCURS AT THIS LOCATION
q.setParameter("uid", uid);
try {
return (User) q.getSingleResult();
} catch (NoResultException ex) {
return null;
}
}
Only for information, this is the initializing code for the entityManager
Code:
/**
* The entity manager factory
*/
private EntityManagerFactory emf = Persistence.createEntityManagerFactory("itbos_server2PU");
/**
* The entity manager
*/
private EntityManager em = emf.createEntityManager();
Does anyone know if it is neccessary to call the close method or not? What will happen if I dont close the entitymanager, might a TooManyConnectionsException or something like this be thrown.
Thx for suggestions