How do I use multiple databases with JPA?

前端 未结 2 405
梦如初夏
梦如初夏 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:

    <?xml version="1.0" encoding="UTF-8"?>
    <persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" 
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
                 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
    
        <persistence-unit name="source-1" transaction-type="RESOURCE_LOCAL">
            <properties>
                <!-- source-1 properties here -->
            </properties>
        </persistence-unit>
    
        <persistence-unit name="source-2" transaction-type="RESOURCE_LOCAL">
            <properties>
                <!-- source-2 properties here -->
            </properties>
        </persistence-unit>
    </persistence>
    

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

    0 讨论(0)
  • 2021-01-14 02:35

    For single datasource jpa will use multiple connections internally.So you don't need to do anything.

    0 讨论(0)
提交回复
热议问题