2015年10月27日 星期二

Criteria1 (Hibernate3.x 七)

※一般使用

Criteria c1 = session.createCriteria(Dept.class);
c1.setFirstResult(0);
c1.setMaxResults(3);
    
@SuppressWarnings("unchecked")
List<Dept> l = c1.list();
for (Dept d : l) {
    System.out.println(d.getDname());
}
System.out.println("----------");
    
Criteria c2 = session.createCriteria(Dept.class);
c2.add(Restrictions.eq("deptno", 20));
Dept d = (Dept) c2.uniqueResult();
System.out.println(d.getDname());
System.out.println("----------");
    
Criteria c3 = session.createCriteria(Dept.class);
c3.add(Restrictions.between("deptno", 20, 40));
for (Object o : c3.list()) {
    System.out.println(((Dept) o).getDname());
}
System.out.println("----------");
    
List<String> inCondition = new ArrayList<String>();
inCondition.add("SALESMAN");
inCondition.add("IT");
inCondition.add("PRESIDENT");
    
Criteria c4 = session.createCriteria(Emp.class);
c4.add(Restrictions.in("job", inCondition));
Iterator<?> it = c4.list().iterator();
while (it.hasNext()) {
    System.out.println(((Emp) it.next()).getEname());
}
System.out.println("----------");
    
Criteria c5 = session.createCriteria(Emp.class);
c5.add(Restrictions.like("job", "%中%"));
Iterator<?> i = c5.list().iterator();
while (i.hasNext()) {
    System.out.println(((Emp) i.next()).getEname());
}

※org.hibernate.criterion.Restrictions還有很多看就會的方法
gt:大於(greater than)
lt:小於(less than)
eq:等於(equal)
ge:大於等於(greater than and equal)
le:小於等於(less than and equal)
ne:不等於(not equal)
※以上六個在xml、jQuery都是類似的
※between、like、in、and、or、not:和SQL一樣
※舊版的Hibernate用得是org.hibernate.criterion.Expression,可是這個方法在3.6版已經過時了

※排序

Criteria criteria = session.createCriteria(Emp.class);
criteria.add(Restrictions.and(
    Restrictions.between("sal", 1500d, 3000d),
    Restrictions.like("ename", "T%"))
);
criteria.addOrder(Order.desc("empno"));
Iterator<?> it = criteria.list().iterator();
while (it.hasNext()) {
    System.out.println(((Emp) it.next()).getEname());
}


※匯總函數

Criteria criteria = session.createCriteria(Emp.class);
ProjectionList plist = Projections.projectionList();
plist.add(Projections.rowCount());
plist.add(Projections.avg("sal"));
plist.add(Projections.groupProperty("deptno"));
criteria.setProjection(plist);
    
@SuppressWarnings("unchecked")
List<Object[]> list = criteria.list();
for (Object[] oA : list) {
    for (Object o : oA) {
        System.out.println(o);
    }
}

※其實就是select count(*), avg(sal) from emp group by deptno

※org.hibernate.criterion.Projections也有很多看就會的方法
如avg、count、distinct、max、min、rowCount、sum等

更多的用法請參考三十五篇

沒有留言:

張貼留言