有没有办法让Spring / JPA自动检测用@Entity注释的类?
背景:
这是我对entityManagerFactory的配置
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" /> </property> </bean>
……这是我的persistence.xml …
<persistence-unit name="foo"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <properties> <property name="hibernate..." value="..."/> <property ... </properties> </persistence-unit>
此配置正常.但是:当我将以下行添加到我的entityManagerFactory配置时
<property name="persistenceXmlLocation" value="META-INF/persistence.xml" />
JPA没有找到使用@Entity注释的类.所以,我得到像这样的例外:
java.lang.IllegalArgumentException: Unknown entity: foo.Bar
其中foo.Bar是一个用@ javax.persistence.Entity注释的类
当我现在添加
<class>foo.Bar</class>
到我的persistence.xml,一切都很好.但是为什么我在使用persistenceXmlLocation时必须在persistence.xml中指定我的类,否则不行?
注意:您可能会问我为什么要使用persistenceXmlLocation:它将解决this problem.
你没有确切地说到底是什么,所以也许我错了,但看起来你觉得我陷入陷阱. persistence.xml文件的位置定义了默认情况下Spring(或任何JPA提供程序)在哪里查找@Entity类.从 JPA spec,第8.2.1节A persistence.xml file defines a persistence unit. The persistence.xml file is located in the
META-INF directory of the root of the persistence unit. It may be used to specify managed persistence
classes included in the persistence unit, object/relational mapping information for those classes, and
other configuration information for the persistence unit and for the entity manager(s) and entity manager factory for the persistence unit. This information may be defined by containment or by reference,
as described below.The object/relational mapping information can take the form of annotations on the managed persistence
classes included in the persistence unit, an orm.xml file contained in the META-INF directory of the
root of the persistence unit, one or more XML files on the classpath and referenced from the persistence.xml file, or a combination of these.
The managed persistence classes may either be contained within the root of the persistence unit; or they
may be specified by reference—i.e., by naming the classes, class archives, or XML mapping files
(which in turn reference classes) that are accessible on the application classpath; or they may be specified by some combination of these means.
因此,尽管该字段称为persistenceXmlLocation,但它可能应该称为persistenceXmlName,因为目的是能够创建具有非标准名称的persistence.xml文件,以便EE容器不会将其拾取.它仍然可以作为查找实体类的标记.