JPA using multiple database schemas JPA using multiple database schemas database database

JPA using multiple database schemas


I had the same problem I solved that with a persistence.xml in which I refer to the needed orm.xml files within I declared the db shema

<persistencexmlns="http://java.sun.com/xml/ns/persistence"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"version="2.0" ><persistence-unit name="schemaOne">    . . .    <mapping-file>ormOne.xml</mapping-file>    . . .</persistence-unit><persistence-unit name="schemaTwo">    . . .    <mapping-file>ormTwo.xml</mapping-file>    . . . </persistence-unit></persistence>

now you can create a EntityManagerFactory for your special schema

EntityManagerFactory emf = Persistence.createEntityManagerFactory("schemaOne");


One thing you can do if you know at deployment is to have 2 orm.xml files. One for schema1 and one for schema2 and then in the persistence.xml you have 2 persistence-units defined. Putting annotations is an anti-pattern if needing to change things like schema


Try following:

puplic class MyClass {  public static final String S1D="S1D";  public static final String S2D="S2D";}@Entity@Table(name = "TABLE1", schema=MyClass.S1D)...@Entity@Table(name = "TABLE2", schema=MyClass.S2D)...