微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在persistence.xml中使用Spring的persistenceXmlLocation

我的问题:

有没有办法让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容器不会将其拾取.它仍然可以作为查找实体类标记.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。