Posted on 2009-08-20 17:26
疯狂 阅读(1573)
评论(0) 编辑 收藏 所属分类:
java
在类级别上配置:
@Entity
@NamedQueries(value = { @NamedQuery(name="query1",query="select a from A a") })
此查询是sessionfactory级别的也就是在创建sessionfactory时候已经处于内存中了
可以在任何地方使用。
调用:
Query q = session.getNamedQuery("query1");
可同时配置多个
@Entity
@NamedQueries(
value = {
@NamedQuery(name="query1",query="select c from A c where c.id=:id") ,
@NamedQuery(name="query2",query="select c from C c where c.id=:id")
}
)
还可以通过hints属性设置查询属性:
例如:设置超时
@NamedQuery(name="query2",query="select c from A c where c.id=?",hints=@QueryHint(name = "timeout", value = "20")
属性说明:
cacheable |
是否可以与二级缓存交互(默认false) |
cacheRegion |
设置缓存名称(默认othewise) |
timeout |
查询超时设定 |
fetchSice |
所获取的结果集大小 |
flushMode |
本次查询所用的刷新模式 |
cacheMode |
本次查询所用的缓存模式 |
readOnly |
是否将本次查询所加载的实体设为只读(默认false) |
comment |
将查询注释下如所生成的sql |
映射本地化查询(普通sql查询):
使用:@NamedNativeQueries和@SqlResultSetMappings
例如:
@Entity
@NamedNativeQueries(value={@NamedNativeQuery(name="nativesql1", query="select * from b where id>1",resultSetMapping="sql1maping")})
@SqlResultSetMappings(value={@SqlResultSetMapping(name="sql1maping",entities={@EntityResult(entityClass=B.class
)})})
public class B{}
测试:
Query q = session.getNamedQuery("nativesql1");
可使用@EntityResult的fields属性来检索固定字段:
@Entity
@NamedNativeQueries(value={@NamedNativeQuery(name="nativesql1", query="select bname from b where id>1",resultSetMapping="sql1maping")})
@SqlResultSetMappings(value={@SqlResultSetMapping(name="sql1maping",entities={@EntityResult(entityClass=B.class,fields={
@FieldResult(name="bname",column="bname")
})})})
public class B{}
测试:
Query q = session.getNamedQuery("nativesql1");
List<B> list = q.list();
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
B a2 = (B) iterator.next();
System.out.println(a2.getBname());
}
此时如果要显示:System.out.println(a2.getId());则会报: could not execute query ---Column 'id1_0_' not found.异常