Hibernate 检索方式2
<!--@page { margin: 2cm }P { margin-bottom: 0.21cm }-->
紧接Hibernate 检索方式(一)
?
以下代码演示了QBC迫切左外连接.
FetchMode.DEFAULT,表示采用映射文件中配置得检索策略.
FetchMode.JOIN
覆盖映射文件中配置的检索策略,在程序中显示指定
迫切左外连接检索策略.
FetchMode.LAZY:覆盖映射文件中配置的检索策略,中程序中
显示指定 延迟检索策略
Listlist = session.createCriteria(Person.class)
.setFetchMode("adds",FetchMode.JOIN)
.add(Restrictions.eq("personName","jack"))
.list();
?
以下代码演示了QBC 内联接
Listlist = 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关键字来实现的.
?
以下代码通过投影查询返回记录数量:
?
Listlist = session.createCriteria(Person.class)
.setProjection(Projections.rowCount())
.add(
Restrictions.like("personName","a",MatchMode.ANYWHERE))
.list();
for(inti=0;i<list.size();i++){
Integercount= (Integer)list.get(i);
System.out.println("---count ="+count);
}
?
?
?
?
?
以下代码通过QBC投影查询返回指定的列:
Criteriacriteria = session.createCriteria(Person.class);
criteria.setProjection(Projections.projectionList().add(
Projections.property("personName")).add(
Projections.property("email")));
Listlist = criteria.list();
Iteratorite = list.iterator();
while(ite.hasNext()) {
Object[] object = (Object[])ite.next();
String personName = (String)object[0];
String email = (String)object[1];
}
?
?
?
在投影查询中使用聚合函数:
Criteriacriteria = 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"));
Listlist = criteria.list();
for(inti = 0;i<list.size();i++){
Object[]object = (Object[])list.get(i);
IntegermaxValue = (Integer)object[0];
IntegerminValue = (Integer)object[1];
IntegersumValue= (Integer)object[2];
Stringpersonname = (String)object[3];
DoubleavgValue = (Double)object[4];
IntegercountValue= (Integer)object[5];
}
?
?
以下代码演示了两个表关联后作投影查询:
Listlist = 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();