开发者

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 stu开发者_StackOverflow中文版ff.

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;
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜