<!-- @page { margin: 2cm } P { margin-bottom: 0.21cm } -->
紧接Hibernate 检索方式(一)
以下代码演示了 QBC 迫切左外连接 .
FetchMode.DEFAULT , 表示采用映射文件中配置得检索策略 .
FetchMode. JOIN
覆盖映射文件中配置的检索策略 , 在程序中显示指定
迫切左外连接检索策略 .
FetchMode.LAZY : 覆盖映射文件中配置的检索策略 , 中程序中
显示指定 延迟检索策略
List list = session.createCriteria(Person. class )
.setFetchMode( "adds" ,FetchMode. JOIN )
.add(Restrictions. eq ( "personName" , "jack" ))
.list();
以下代码演示了 QBC 内联接
List list = session.createCriteria(Adds.class)
.createAlias("person", "p")
.add(Restrictions.like("p.personName", "a", MatchMode.ANYWHERE))
.add(Restrictions.like("this.addName", "an", MatchMode.ANYWHERE))
.list();
投影查询是指查询结果仅包括部分实体或者实体的部分属性 . 投影是通过 select 关键字来实现的 .
以下代码通过投影查询返回记录数量 :
List list = session.createCriteria(Person. class )
.setProjection(Projections. rowCount ())
.add(
Restrictions. like ( "personName" , "a" , MatchMode. ANYWHERE ))
.list();
for ( int i=0;i<list.size();i++){
Integer count = (Integer)list.get(i);
System. out .println( "--- count =" +count);
}
以下代码通过 QBC 投影查询返回指定的列 :
Criteria criteria = session.createCriteria(Person. class );
criteria.setProjection(Projections. projectionList ().add(
Projections. property ( "personName" )).add(
Projections. property ( "email" )));
List list = criteria.list();
Iterator ite = list.iterator();
while (ite.hasNext()) {
Object[] object = (Object[])ite.next();
String personName = (String)object[0];
String email = (String)object[1];
}
在投影查询中使用 聚合函数 :
Criteria criteria = session.createCriteria(Person. class );
criteria.setProjection(
Projections. projectionList ()
.add(Projections. max ( "personid" ))
.add(Projections. min ( "personid" ))
.add(Projections. sum ( "personid" ))
.add(Projections. property ( "personName" ))
.add(Projections. avg ( "personid" ))
.add(Projections. count ( "personid" ))
.add(Projections. groupProperty ( "personName" )))
.addOrder(Order. asc ( "personName" ));
List list = criteria.list();
for ( int i = 0;i<list.size();i++){
Object[] object = (Object[])list.get(i);
Integer maxValue = (Integer)object[0];
Integer minValue = (Integer)object[1];
Integer sumValue= (Integer)object[2];
String personname = (String)object[3];
Double avgValue = (Double)object[4];
Integer countValue = (Integer)object[5];
}
以下代码演示了两个表关联后作投影查询 :
List list = session.createCriteria(Person.class)
.createAlias("adds","a")
.add(Restrictions.like
("personName", "a", MatchMode.ANYWHERE))
.add(Restrictions.like
("a.addName", "an", MatchMode.ANYWHERE))
.setProjection(Projections.projectionList()
.add(Projections.property("personid"))
.add(Projections.property("personName"))
.add(Projections.property("a.addsid"))
.add(Projections.property("a.addName")))
.list();