Spring LocalContainerEntityManagerFactoryBean scanForPackages和Hibernate包级别类型定义

时间:2013-05-05 06:24:57

标签: spring jpa hibernate-mapping

在Spring 3.1及更高版本中,LocalContainerEntityManagerFactoryBean应该能够在没有persistence.xml的情况下配置JPA EntityManagerFactory。该配置包含在LocalContainerEntityManagerFactoryBean的bean定义中。

当我使用packagesToScan方法告诉工厂bean在哪里扫描我的实体类时,它似乎没有拿起我在包级别定义的Hibernate type definitions

package-info.java:

@org.hibernate.annotations.TypeDefs({
    @org.hibernate.annotations.TypeDef(name = "TypeA", typeClass = com.foo.type.A.class),
    @org.hibernate.annotations.TypeDef(name = "TypeB", typeClass = com.foo.type.B.class) }) package com.foo.type;

弹簧jpa.xml:

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" lazy-init="true">
    <property name="dataSource" ref="dataSource" />
    <property name="persistenceProviderClass" value="org.hibernate.ejb.HibernatePersistence"/>
    <property name="jpaVendorAdapter">
      <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
    </property>       
    <property name="jpaPropertyMap">
        <map>                               
            <entry key="hibernate.dialect" value="com.foo.FooDialect" />
            <entry key="hibernate.default_schema" value="dba"/>             
            <entry key="hibernate.cache.use_query_cache" value="false"/>
            <entry key="hibernate.cache.use_second_level_cache" value="true"/>
            <entry key="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory"/>
            <entry key="net.sf.ehcache.configurationResourceName" value="META-INF/ehcache.xml" />
            <entry key="javax.persistence.validation.factory" value-ref="validator"/>
        </map>
    </property>
    <property name="packagesToScan"> 
        <list>
            <value>com.foo.domain</value>
            <value>com.foo.type</value>
        </list>
    </property>             
</bean>

有没有办法让这项工作?

1 个答案:

答案 0 :(得分:-1)

我发现在包级别typedef中添加@MappedSuperclass注释会导致Hibernate查找并处理它们。它似乎不是一个非常漂亮的解决方案,所以如果存在,我仍然在寻找更好的方法。

package-info.java:

@MappedSuperclass // <---HACK TO CAUSE HIBERNATE TO NOTICE THESE TYPE DEFS
@TypeDefs({
    @TypeDef(name = "TypeA", typeClass = com.foo.type.A.class),
    @TypeDef(name = "TypeB", typeClass = com.foo.type.B.class) 
}) 
package com.foo.type;

import javax.persistence.MappedSuperclass;