How do I use multiple databases with JPA?

前端 未结 2 415
梦如初夏
梦如初夏 2021-01-14 02:14

I need two or more than two connections in my web application using jpa

2条回答
  •  失恋的感觉
    2021-01-14 02:27

    To use different data sources, add multiple persistence units (say, source-1 and source-2 in persistence.xml and create multiple EntityManagerFactoryes by name):

    EntityManagerFactory emf1 = Persistence.createEntityManagerFactory("source-1");
    EntityManagerFactory emf2 = Persistence.createEntityManagerFactory("source-2");
    

    or, if you're working on Spring or Java EE application server, inject them by name also:

    @PersistenceUnit(name = "source-1")
    EntityManagerFactory emf1;
    
    @PersistenceContext(unitName = "source-2") // as an option
    EntityManager em2;
    

    persistence.xml will thus look like the following:

    
    
    
        
            
                
            
        
    
        
            
                
            
        
    
    

    Example of how to configure persistence unit, create EntityManager to manage entities and execute queries can be found here.

提交回复
热议问题