是否有办法将HQL命名查询外部化为外部文件。我有太多的命名查询,并且在我的实体类的头部使用@NamedQueries
和@NamedQuery
会受到伤害。
有没有办法外化到多个文件?
答案 0 :(得分:10)
您可以将查询放入package-info.java
类,例如域对象的根包中。但是,您必须使用Hibernate自己的@NamedQueries
和@NamedQuery
注释,而不是来自javax.persistence
的注释。
示例package-info.java
文件:
@org.hibernate.annotations.NamedQueries({
@org.hibernate.annotations.NamedQuery(
name = "foo.findAllUsers",
query="from Users")
})
package com.foo.domain;
然后,您必须将包添加到AnnotationConfiguration
。我使用Spring,因此需要设置annonatedPackages
属性:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="annotatedClasses">
<list>
...
</list>
</property>
<property name="annotatedPackages">
<list>
<value>com.foo.domain</value>
</list>
</property>
您也可以将类型和过滤器定义放在同一个文件中。
答案 1 :(得分:3)
我认为这不可能,因为Annotation属性/属性值必须在编译时可用。因此,不能将字符串外部化为需要通过某种过程读入的文件。
我试图找出package-info.java是否有能够提供的东西,但找不到任何东西。
组织的另一种策略可能是将查询作为常量存储在类中。
在您的实体类中:
@NamedQuery(name="plane.getAll", query=NamedQueries.PLANE_GET_ALL)
然后为查询常量定义一个类:
public class NamedQueries {
...
public static final String PLANE_GET_ALL = "select p from Plane p";
...
}
答案 2 :(得分:3)
也许这不是作者所要求的(外化到非java文件),但这就是我解决它的方法:
1。)在我的应用程序上下文xml文件中,我将mappingResources
添加到sessionFactory
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>META-INF/Country.hbm.xml</value>
</list>
</property>
<property name="annotatedClasses">
<util:list>
<value>com.example.Country</value>
</util:list>
</property>
<property name="hibernateProperties" ref="hibernateProperties" />
</bean>
在Country.hbm.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">
<entity class="com.example.Country">
<named-query name="countryFindByCode">
<query><![CDATA[
select c
from Country c
where c.code = :code
]]></query>
</named-query>
<named-query name="countryFindByName">
<query><![CDATA[
select c
from Country c
where c.name = :name
]]></query>
</named-query>
</entity>
</entity-mappings>
我用它来定义命名查询,其余的实体配置都在注释中。
也许这有助于某人。
答案 3 :(得分:-2)
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>META-INF/Country.hbm.xml</value>
</list>
</property>
<property name="annotatedCla
from Country c
where c.name = :name
]]></query>
</named-query>
</entity>
</entity-mappings>