欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Hibernate中的Criteria查询

程序员文章站 2022-04-15 22:21:47
...

第一、前言
阅读本篇文章之前,请先阅读:Hibernate中的HQL查询
第二、QBC简介
QBC:Query By Criteria,它是一种更加面向对象的查询方式,它把生成语句的过程全都融入到方法之中了。效率比HQL低。
第三、代码演示
1、基本查询

package com.demo;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.demo.dto.Teacher;
import com.demo.util.HibernateUtil;
/**
 * 测试类
 * @author shixiangcheng
 * 2020-07-04
 */
public class Test {
	public static void main(String[] args) {
		Session s=HibernateUtil.getCurrentSession();
		Transaction tx=s.beginTransaction();
		//1.获取Criteria对象
		Criteria c=s.createCriteria(Teacher.class);
		//2.获取结果
		List<Teacher> list=c.list();
		for(Teacher t:list) {
			System.out.println(t);
		}
		tx.commit();
	}
}

运行结果

Hibernate: 
    select this_.id as id1_0_0_,this_.name as name2_0_0_ from t_teacher this_
[id=1,name=王一]
[id=2,name=王二]
[id=3,name=王三]
[id=4,name=王四]
[id=5,name=王五]
[id=6,name=王六]
[id=7,name=王七]

2、条件查询

//1.获取Criteria对象
Criteria c=s.createCriteria(Teacher.class);
c.add(Restrictions.eq("id", 5));

运行结果

Hibernate: 
    select this_.id as id1_0_0_,this_.name as name2_0_0_ from t_teacher this_ where this_.id=?
[id=5,name=王五]

3、排序分页和统计查询
排序

//按id降序
c.addOrder(Order.desc("id"));
//设置分页条件
c.setFirstResult(2);//设置查询的开始记录索引
c.setMaxResults(2);//设置每次查询的条数

运行结果

Hibernate: 
    select this_.id as id1_0_0_,this_.name as name2_0_0_ from t_teacher this_ order by this_.id desc limit ?,?
[id=5,name=王五]
[id=4,name=王四]

统计

//1.获取Criteria对象
Criteria c=s.createCriteria(Teacher.class);
//设置聚合函数
//c.setProjection(Projections.rowCount());
//按照某一字段统计
c.setProjection(Projections.count("id"));
//2.获取结果
Long count=(Long)c.uniqueResult();
System.out.println(count);

运行结果

Hibernate: 
    select count(this_.id) as y0_ from t_teacher this_
7