[英]How to write named queries with xml in Hibernate/JPA?
我可以使用注釋使用命名查詢,沒有任何問題。 但是,當我嘗試切換到orm.xml文件以外部化我的應用程序時,找不到我的命名查詢,該查詢位於類路徑META-INF目錄下的User.orm.xml
文件中。 我的User.orm.xml
文件的完整路徑是src\\main\\resources\\META-INF\\User.orm.xml
當我嘗試運行查詢時,出現以下異常,
java.lang.IllegalArgumentException: No query defined for that name [READ_ALL_USERS]
[artifact:mvn] at org.hibernate.jpa.spi.AbstractEntityManagerImpl.buildQueryFromName(AbstractEntityManagerImpl.java:788)
我在src/main/resources/META-INF
下的persistence.xml
看起來像這樣,
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
version="2.0">
<persistence-unit name="webPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.spring.model.User</class>
<properties>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/spring?zeroDateTimeBehavior=convertToNull"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLInnoDBDialect" />
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.connection.password" value="password"/>
</properties>
</persistence-unit>
</persistence>
我的User.orm.xml
文件具有以下命名查詢,
<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_2_0.xsd" version="2.0">
<named-query name="READ_ALL_USERS">
<query>SELECT user from com.spring.User user</query>
</named-query>
</entity-mappings>
我查看了這個問題,它建議將 orm.xml 文件保留在模型類所在的位置。 但這對我不起作用。 上面的代碼有什么問題。
我還在我的 persistence.xml 中包含了 User.orm.xml 文件的映射,它已經在我的 META-INF 目錄下的類路徑中。 我嘗試了以下文件映射,但沒有一個檢測到我的 xml 文件,
<mapping-file>User.orm.xml</mapping-file>
<mapping-file>/META-INF/User.orm.xml</mapping-file>
<mapping-file>classpath:User.orm.xml</mapping-file>
您必須在<persistence-unit>
元素內添加一個<mapping-file>
<persistence-unit>
元素。
示例: <persistence-unit> <mapping-file>User.orm.xml</mapping-file> </persistence-unit>
來源: https : //docs.jboss.org/hibernate/entitymanager/3.5/reference/en/html/configuration.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.