0

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?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
nerdlyist
  • 2,842
  • 2
  • 20
  • 32
  • Multiple databases is a most used case. Maybe someone else saw other applications. (And please consider that your `getEntityManagerFor()` code is dangerously thread-unsafe) – Alex Salauyou Mar 10 '16 at 18:58
  • @SashaSalauyou that is what I assumed and thanks for the pointer I was curious if what I was creating would bite me in the butt later. – nerdlyist Mar 10 '16 at 19:27

1 Answers1

0

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.

Bazz
  • 11
  • 1
  • So would you are say one for prod, stage and test? How would that work in the code for building your EntitiyManager? – nerdlyist Mar 11 '16 at 16:40