JPA using multiple database schemas

前端 未结 6 1023
花落未央
花落未央 2020-12-01 05:13

I\'m having a bit of trouble with one particular issue using JPA/Spring:

How can I dynamically assign a schema to an entity?

We have TABLE1 that belongs to s

相关标签:
6条回答
  • 2020-12-01 05:56

    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

    <persistence
    xmlns="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");
    
    0 讨论(0)
  • 2020-12-01 05:58

    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

    0 讨论(0)
  • 2020-12-01 06:02

    when you create a datasource, you may be able to initialize the connection to use different schema

    e.g. for weblogic

    Specify default schema for JDBC pool in weblogic/oracle

    0 讨论(0)
  • 2020-12-01 06:04

    You could have two DataSource declarations (one for each schema) in your context.xml and define two persistence units using this datasources. The context.xml can then be different on the appservers of the different environments.

    0 讨论(0)
  • 2020-12-01 06:08

    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)
    ...
    
    0 讨论(0)
  • 2020-12-01 06:10

    Annotation arguments have to be final and can therefore not be changed at runtime.

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