Mapping the same entity class to two banks

1

Good afternoon Terrans,

I'm a beginner in Java and I have the following situation. I have two databases, where I will transfer the records from one bank to another. Is it possible to have a Entity class mapped by the two banks?

Comments:

  • The application is using the EntityManagerFactory and the same I instantiate an EntityManger.
asked by anonymous 25.08.2016 / 23:01

1 answer

2

Yes, it does. In JPA you use persistence units, which represent specific banks. If you want to specify more than one bank, you can only declare more than one persistence unit (PU) and create the entity managers for each one. The persistence.xml file that declares the PUs looks like this:

<persistence-unit name="pu1">
<properties>
        <property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost/banco1" />
        <property name="javax.persistence.jdbc.user" value="admin" />
        <property name="javax.persistence.jdbc.password" value="123456" />

<persistence-unit name="pu2">
<properties>
        <property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost/banco2" />
        <property name="javax.persistence.jdbc.user" value="admin" />
        <property name="javax.persistence.jdbc.password" value="123456" />

Then to reference an entity that is in bank 1 you only need to instantiate the pu1 in the creation of the entity manager:

EntityManager emPU1 = Persistence.createEntityManagerFactory("pu1").createEntityManager();

Now for the entity that is in bank 2 just refer to pu2:

EntityManager emPU2 = Persistence.createEntityManagerFactory("pu2").createEntityManager();

After consulting both entities, you can make your DE-PARA and persist as you wish the final result. I hope I have helped ^^

    
31.08.2016 / 03:23