Hibernate 4.3加载所有hbm文件,即使它们未在持久性单元中声明

时间:2014-06-23 16:18:34

标签: java spring hibernate jpa

我正在尝试使用以下配置为JPA和Spring 4配置hibernate 4.3的测试:

<bean id="em" class="LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource" />
            <property name="jpaVendorAdapter">
                  <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
            </property>
    <property name="persistenceXmlLocation"
        value="classpath:integrations/hibernate4/jpa/persistence.xml" />
</bean>

现在,持久性配置如下所示:

<persistence-unit name="test" >
    <class>hibernate4.jpa.JpaEntity</class>
    <class>hibernate4.jpa.JpaHiLoEntity</class>
    <properties>
        <property name="hibernate.hbm2ddl.auto" value="create" />
    </properties>
    <exclude-unlisted-classes>true</exclude-unlisted-classes>
</persistence-unit>

如果我使用hibernate 4.2.4运行上面的一切都运行正常,但是使用4.3上面的设置会加载所有hbm.xml资源文件,其中一些引用类路径中不存在的类,导致{{1} }。

有谁知道改变行为的原因是什么以及如何阻止hibernate扫描hbm.xml文件(packagesToScan属性也不起作用)?

3 个答案:

答案 0 :(得分:4)

我也遇到了这个问题。 hibernate.archive.autodetection 属性控制Hibernate将自动扫描的内容:

  1. 如果属性未定义,将包含hbm文件,并且除非<exclude-unlisted-classes>设置为true,否则将包含带注释的类。
  2. 如果属性的值包含&#34; hbm&#34;然后将包含.hbm.xml文件。否则他们不会成为。
  3. 如果值包含&#34; class&#34;,则将包含类路径上的任何带注释的类。否则他们不会成为。
  4. 如果属性完全定义,无论其值如何,都会影响Hibernate的行为。请参阅org.hibernate.jpa.boot.scan.internal.StandardScanOptions构造函数。
  5. 出于我的目的,我需要持久性单元仅包含<class>元素中明确列出的实体。为此,我使用&#34; none&#34;:

    的值定义了属性
    <persistence-unit name="num2" transaction-type="RESOURCE_LOCAL">
        ...
        <properties>
            ...
            <property name="hibernate.archive.autodetection" value="none" />
        </properties>
    </persistence-unit>
    

    不幸的是,我在这个属性上找到的唯一文档是stable release,无论是什么。在Hibernate 4.3的文档中没有提到它,但这是我使用的版本,我可以确认该属性有效。

答案 1 :(得分:0)

此外,您还可以在不使用文件em的情况下配置bean persistence.xml。 e.g:

<bean id="em" 
      class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" 
      p:dataSource-ref="dataSource" 
      p:packagesToScan="···.model">

    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" 
              p:showSql="false" 
              p:databasePlatform="org.hibernate.dialect.SQLServerDialect" />
    </property>

    <property name="jpaProperties">
        <props>
            <prop key="hibernate.format_sql">true</prop>
        </props>
    </property>

</bean>

答案 2 :(得分:0)

如果您的班级在要扫描的包中,exclude-unlisted-classes不起作用,例如你想让它注册,但不想要它的hbm.xml。

我修复了使用hibernate属性hibernate.archive.autodetection设置为class,使Hibernate只扫描类而不是映射文件。

<properties>
    <property name="hibernate.archive.autodetection" value="class" />
</properties