How is a Hibernate EntityManager
to be used in a multi thread application (eg each client connection starts it's own thread on the server).
Should EntityManager only created once by EntityManagerFactory, like:
private static EntityManagerFactory emf = Persistence.createEntityManagerFactory("unit");
private static EntityManager em = emf.createEntityManager();
public static EntityManager get() {
return em;
}
Or do I have to recreate the entitymanger for every thread, and for every transaction that closes the EM?
My CRUD methods will look like this:
public void save(T entity) {
em.getTransaction().begin();
em.persist(entity);
em.getTransaction().commit();
em.close();
}
public void delete(T entity) {
em.getTransaction().begin();
em.remove(entity);
em.getTransaction().commit();
em.close();
}
Would I havew to run emf.createEntityManager()
before each .begin()
? Or am I then getting into trouble because each is creating an own EntityManager instance with it's own cache?