问题描述
我在使用 JPA/Spring 时遇到了一个特定问题:
I'm having a bit of trouble with one particular issue using JPA/Spring:
如何为实体动态分配架构?
How can I dynamically assign a schema to an entity?
我们有属于架构 AD 的 TABLE1 和属于 BD 的 TABLE2.
We have TABLE1 that belongs to schema AD and TABLE2 that is under BD.
@Entity
@Table(name = "TABLE1", schema="S1D")
...
@Entity
@Table(name = "TABLE2", schema="S2D")
...
模式可能不会硬编码在注释属性中,因为它取决于环境 (Dev/Acc/Prd).(接受模式是 S1A 和 S2A)
The schemas may not be hardcoded in an annotation attribute as it depends on the environment (Dev/Acc/Prd). (In acceptance the schemas are S1A and S2A)
我怎样才能做到这一点?是否可以像这样指定某种占位符:
How can I achieve this? Is it possible to specify some kind of placeholders like this:
@Entity
@Table(name = "TABLE1", schema="${schema1}")
...
@Entity
@Table(name = "TABLE2", schema="${schema2}")
...
以便根据驻留在环境中的属性文件替换模式?
so that schemas are replaced based on a property file residing in the environment?
干杯
推荐答案
我遇到了同样的问题,我用persistence.xml 解决了这个问题,我在声明db shema 时引用了所需的orm.xml 文件
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>
现在您可以为您的特殊架构创建一个 EntityManagerFactory
now you can create a EntityManagerFactory for your special schema
EntityManagerFactory emf = Persistence.createEntityManagerFactory("schemaOne");
这篇关于JPA 使用多个数据库模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!