Search code examples
hibernatejpahibernate-entitymanager

Hibernate on non-managed environment


I got an small problem, I always worked with Hibernate and Spring on Web stuff with a GenericDAO pattern, now I'm using Hibernate for a GUI app which doesn't use anything like EJB and stuff.

My main problem is I used to have this

@PersistenceContext(unitName = "persistenceUnit") private EntityManager em;

but now I do thing this way:

private EntityManagerFactory emf = Persistence.createEntityManagerFactory("persistenceUnit"); private EntityManager em = emf.createEntityManager();

Just came to notice a big flaw I have is that whenever I inherit this GenericDAO class I'm creating one EntityManagerFactory each time, what should I do?

EDIT:

Agree this would be the neatest way to solve it?

private EntityManagerFactory emf;
private static final Connector INSTANCE = new Connector();

public static Connector getInstance() {
    return INSTANCE;
}   

private Connector(){        
    emf = Persistence.createEntityManagerFactory("persistenceUnit");
}

public EntityManagerFactory getEmf() {      
return emf;
}

Solution

  • You can still use dependency injection pattern without Spring or other container - create EntityManagerFactory in a single place and inject it into DAO objects when you create them.