hibernate annoation (十 映射查询)
当前位置:以往代写 > JAVA 教程 >hibernate annoation (十 映射查询)
2019-06-14

hibernate annoation (十 映射查询)

hibernate annoation (十 映射查询)

副标题#e#

在类级别上设置:

Java代码

 @Entity
 @NamedQueries(value = { @NamedQuery(name="query1",query="select a from A a") })

此查询是sessionfactory级此外也就是在建设sessionfactory时候已经处于内存中了

可以在任那里所利用。

挪用:

Java代码

Query q = session.getNamedQuery("query1");

可同时设置多个

Java代码

@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属性配置查询属性:

譬喻:配置超时

Java代码

@NamedQuery(name="query2",query="select c from A c where c.id=?",[email protected](name = "timeout", value = "20")

属性说明:

cacheable 是否可以与二级缓存交互(默认false)
cacheRegion 配置缓存名称(默认othewise)
timeout 查询超时设定
fetchSice 所获取的功效集巨细
flushMode 本次查询所用的刷新模式
cacheMode 本次查询所用的缓存模式
readOnly 是否将本次查询所加载的实体设为只读(默认false)
comment 将查询注释下如所生成的sql


#p#副标题#e#

映射当地化查询(普通sql查询):

利用:@NamedNativeQueries和@SqlResultSetMappings

譬喻:

Java代码

@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{}

测试:

Java代码

Query q = session.getNamedQuery("nativesql1");

可利用@EntityResult的fields属性来检索牢靠字段:

Java代码

@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{}

测试:

Java代码

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.异常

    关键字:

在线提交作业