【问题标题】:Settng the schema of a Hibernate entity extra to the default schema configuration将 Hibernate 实体的架构设置为默认架构配置
【发布时间】:2016-09-21 07:47:14
【问题描述】:

我有一个 Hibernate / Spring 4 应用程序,其中已经配置了实体类的默认模式,例如它们最终映射为testschema.table 或prodschema.table。

但是,还有另一个实体类需要自己的可配置架构,例如只有这个实体必须映射到testschema2.anothertable 或prodschema2.anothertable。

最好是这样的:

@Entity
@Table(name="anothertable", schema = "${db.AntherEntitySchema}") 
public class AnotherEntity {
  // ..
}

从属性文件中注入模式的位置,但这样的功能似乎只适用于@Value 注释。 知道如何进行吗?

【问题讨论】:

    标签: spring hibernate configuration


    【解决方案1】:

    我们通过这个applicationContextPersistence.ctx.xml解决了

    <bean id="entityManagerFactory"
          class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="persistenceXmlLocation"
                  value="classpath:META-INF/persistence-${env}.xml" />
        <!-- .. -->
    </bean>
    

    Spring 可以替换属性文件中的 ${} 表达式。

    然后我们有一个具有特定 orm-dev.xml 的 persistence-dev.xml 等:

    <?xml version="1.0" encoding="UTF-8"?>
    <persistence 
        version="2.0" 
        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">
        <persistence-unit name="fooUnit" transaction-type="RESOURCE_LOCAL">
            <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
            <mapping-file>META-INF/orm-dev.xml</mapping-file>
        </persistence-unit>
        <!-- .. -->
    </persistence>
    

    orm-dev.xml 现在负责实体映射:

    <?xml version="1.0" encoding="UTF-8" ?>
    
    <entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm    
       http://java.sun.com/xml/ns/persistence/orm_1_0.xsd"
        version="1.0">
    
        <description> XML Mapping file</description>
    
        <package>foo.server.model</package>
    
        <entity class="AnotherEntity">
            <table schema="testschema2" name="anothertable" />
            <attributes>
               <!-- .. -->
            </attributes>
        </entity>
    </entity-mappings>
    

    最后,我们从 AnotherEntity POJO 中删除了映射注解,因为这个注解现在通过 orm-dev.xml 文件映射。其他实体类保留了它们的注释。

    注意:我们使用 Eclipse 的 Spring Tool Suite 风格。此 IDE 需要一个 persistence.xml,因此为了摆脱错误消息,我们保留了一个最小的 persistence.xml,这样就不必记住停用验证器的 IDE 选项。

    【讨论】:

      猜你喜欢
      • 2011-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-27
      • 2016-02-04
      • 1970-01-01
      • 2011-08-23
      • 1970-01-01
      相关资源
      最近更新 更多