How to inject persistence context to different data source programmatically

前端 未结 4 1083
时光说笑
时光说笑 2020-12-03 06:01

In standard EJB 3, when injecting entity manager, persistence unit (which refers to datasource) is hardcoded into annotation: (or alternatively xml file)

@Pe         


        
4条回答
  •  温柔的废话
    2020-12-03 06:38

    • Configure required data-sources & persistent-units in persistence.xml.
    
          PERSISTENCE_PROVIDER
              java:DATA_SOURCE_NAME
    
    
     -- other units  
    

    Now at runtime you can build entity-manager for the required persistence-unit. Create separate persistence-units for each data-source.

    //---
    EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnitName);
    EntityManager em = emf.createEntityManager();
    //---
    
    • Else you can also build factory by providing a map of properties like db-url, userName etc.
    createEntityManagerFactory(persistenceUnitName,propertiesMap);
    

    This will create and return an EntityManagerFactory for the named persistence unit using the given properties. Therefore you can change the properties at runtime accordingly.

提交回复
热议问题