I am creating a Java EE application and have setup my persistence using hibernate. Since I do not see this app being all that big I do not see the point in using EJBs so I created a PersistenceUtil class to manage my EntityManagerFactory.
Something like this:
private static HashMap<String, Object> emfMap = new HashMap<String, Object>();
public static EntityManager getEntityManagerFor(String unitName){
if(!emfMap.isEmpty() || !emfMap.containsKey(unitName)){
EntityManagerFactory emf = Persistence.createEntityManagerFactory(unitName);
emfMap.put(unitName, emf);
return emf.createEntityManager();
} else {
//return the one that exists...
}
So since there can be more then one persistent-unit I can lazily load them as they are used.
I have created it this way because I understand there can be multiple persistent-units. What I do not understand and cannot seem to find the answer for is what would make me create another persistent-unit? One thing would be multiple databases I would assume but are there any other division point?
Usually for different databases you create a separate persistence unit. However it is not the only reason. You can design multiple persistence unit for the same database, but with different configuration or classes, i.e. when you deploy your application on multiple environments.