在類級別上配置:
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=?",hints=@QueryHint(name = "timeout", value = "20")
屬性說明:
cacheable 是否可以與二級緩存交互(默認false)
cacheRegion 設置緩存名稱(默認othewise)
timeout 查詢超時設定
fetchSice 所獲取的結果集大小
flushMode 本次查詢所用的刷新模式
cacheMode 本次查詢所用的緩存模式
readOnly 是否將本次查詢所加載的實體設為只讀(默認false)
comment 將查詢注釋下如所生成的sql
映射本地化查詢(普通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.異常