gpt4 book ai didi

spring - 在persistence.xml 中使用没有 的Spring 持久性Xml 位置

转载 作者:行者123 更新时间:2023-12-01 05:38:51 24 4
gpt4 key购买 nike

我的问题:

有没有办法告诉 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容器就不会捡到它。它仍然作为在哪里寻找实体类的标记。

关于spring - 在persistence.xml 中使用没有<class> 的Spring 持久性Xml 位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6988353/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com