QBC检索

QBC(Query By Criteria)是Hibernate提供的另一种检索对象的方式,它主要由Criteria接口、Criterion接口和Expression类组成。

Criteria接口是Hibernate API中的一个查询接口,它需要由session进行创建。一个单独的查询就是Criterion接口的一个实例,用于限制Criteria对象的擦查询,在Hibernate中Criterion对象的创建通常是通过Restrictions工厂类完成的,它提供了条件查询方法。

Criterion是Criteria的查询条件,在Criteria中提供了add(Criterion criterion)方法来添加查询条件。

使用QBC检索对象的实例代码,如下所示

 //创建criteria对象Criteria criteria = session.createCriteria(Customer.class);//设定查询条件Criterion criterion = Restrictions.eq("id",1);//添加查询条件criteria.add(criterion);//执行查询,返回查询结果List<Customer> cs = criteria.list();

上述代码中查询的是id为1的Customer对象。

QBC检索是使用Restricions对象编写查询条件的,在Restrictions类中提供了大量的静态方法来创建查询条件。

–》Restrictions常量和方法

准备工作

创建一个Customer类:

package pers.zhang.domain;public class Customer {private Long cust_id;private String cust_name;private String cust_source;private String cust_industry;private String cust_level;private String cust_linkman;private String cust_phone;private String cust_mobile;public Long getCust_id() {return cust_id;}public void setCust_id(Long cust_id) {this.cust_id = cust_id;}public String getCust_name() {return cust_name;}public void setCust_name(String cust_name) {this.cust_name = cust_name;}public String getCust_source() {return cust_source;}public void setCust_source(String cust_source) {this.cust_source = cust_source;}public String getCust_industry() {return cust_industry;}public void setCust_industry(String cust_industry) {this.cust_industry = cust_industry;}public String getCust_level() {return cust_level;}public void setCust_level(String cust_level) {this.cust_level = cust_level;}public String getCust_linkman() {return cust_linkman;}public void setCust_linkman(String cust_linkman) {this.cust_linkman = cust_linkman;}public String getCust_phone() {return cust_phone;}public void setCust_phone(String cust_phone) {this.cust_phone = cust_phone;}public String getCust_mobile() {return cust_mobile;}public void setCust_mobile(String cust_mobile) {this.cust_mobile = cust_mobile;}@Overridepublic String toString() {return "Customer [cust_id=" + cust_id + ", cust_name=" + cust_name + "]";}
}

配置ORM元数据:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="pers.zhang.domain" ><class name="Customer" table="cst_customer" ><id name="cust_id"  ><generator class="identity"></generator></id><property name="cust_name" column="cust_name" ></property><property name="cust_source" column="cust_source" ></property><property name="cust_industry" column="cust_industry" ></property><property name="cust_level" column="cust_level" ></property><property name="cust_linkman" column="cust_linkman" ></property><property name="cust_phone" column="cust_phone" ></property><property name="cust_mobile" column="cust_mobile" ></property></class>
</hibernate-mapping>

向表中插入数据:

基本查询–查询所有
@Test//基本查询public void fun1(){Session session = HibernateUtils.openSession();Transaction tx = session.beginTransaction();//-------------------------------------------//查询所有的Customer对象Criteria criteria = session.createCriteria(Customer.class);   List<Customer> list = criteria.list();System.out.println(list);//-------------------------------------------tx.commit();session.close();}

运行JUnit测试输出:

Hibernate: selectthis_.cust_id as cust_id1_0_0_,this_.cust_name as cust_nam2_0_0_,this_.cust_source as cust_sou3_0_0_,this_.cust_industry as cust_ind4_0_0_,this_.cust_level as cust_lev5_0_0_,this_.cust_linkman as cust_lin6_0_0_,this_.cust_phone as cust_pho7_0_0_,this_.cust_mobile as cust_mob8_0_0_ fromcst_customer this_
[Customer [cust_id=1, cust_name=Google], Customer [cust_id=2, cust_name=联想], Customer [cust_id=3, cust_name=百度], Customer [cust_id=4, cust_name=阿里巴巴], Customer [cust_id=5, cust_name=腾讯]]
条件查询

条件查询需要调用criteria.add()方法,参数为Restricions对象。
–》Restrictions常量和方法

@Test//条件查询// >              gt// >=             ge// <               lt// <=             le// ==               eq// !=                ne// in             in// between and        between// like          like// is not null      isNotNull// is null         isNull// or             or// and                andpublic void fun2(){Session session = HibernateUtils.openSession();Transaction tx = session.beginTransaction();//-------------------------------------------//创建criteria查询对象Criteria criteria = session.createCriteria(Customer.class);//添加查询参数 => 查询cust_id为1的Customer对象criteria.add(Restrictions.eq("cust_id", 1l));//执行查询获得结果Customer c = (Customer) criteria.uniqueResult();System.out.println(c);//-------------------------------------------tx.commit();session.close();}

运行JUnit测试输出:

Hibernate: selectthis_.cust_id as cust_id1_0_0_,this_.cust_name as cust_nam2_0_0_,this_.cust_source as cust_sou3_0_0_,this_.cust_industry as cust_ind4_0_0_,this_.cust_level as cust_lev5_0_0_,this_.cust_linkman as cust_lin6_0_0_,this_.cust_phone as cust_pho7_0_0_,this_.cust_mobile as cust_mob8_0_0_ fromcst_customer this_ wherethis_.cust_id=?
Customer [cust_id=1, cust_name=Google]
分页查询

QBC的分页查询与MySql的limit十分相似,使用两个方法:
1.criteria.setFirstResult(arg),设置第一条结果从哪个索引开始,相当于limit中的第一个?。
2.criteria.setMaxResults(arg),设置一次查询多少条数据,相遇于limit中的第二个?。

 @Test//分页查询public void fun3(){Session session = HibernateUtils.openSession();Transaction tx = session.beginTransaction();//-------------------------------------------Criteria criteria = session.createCriteria(Customer.class);//设置分页信息 limit ?,?  从第1条开始查,查询2条数据criteria.setFirstResult(1);criteria.setMaxResults(2);List<Customer> list = criteria.list();System.out.println(list);//-------------------------------------------tx.commit();session.close();}

运行JUnit测试输出:

Hibernate: selectthis_.cust_id as cust_id1_0_0_,this_.cust_name as cust_nam2_0_0_,this_.cust_source as cust_sou3_0_0_,this_.cust_industry as cust_ind4_0_0_,this_.cust_level as cust_lev5_0_0_,this_.cust_linkman as cust_lin6_0_0_,this_.cust_phone as cust_pho7_0_0_,this_.cust_mobile as cust_mob8_0_0_ fromcst_customer this_ limit ?,?
[Customer [cust_id=2, cust_name=联想], Customer [cust_id=3, cust_name=百度]]
排序查询

条件查询需要调用criteria.addOrder()方法,参数为Order对象。
Order类的常用方法:作为查询容器的参数

方法名称 描述 使用
Order.asc 升序 Order.asc(String propertyName)
Order.desc 降序 Order.desc(String propertyName)
@Testpublic void fun4() {Session session = HibernateUtils.openSession();Transaction tx = session.beginTransaction();//-------------------------------------------Criteria criteria = session.createCriteria(Customer.class);//设置排序规则 按id降序排序criteria.addOrder(Order.desc("cust_id"));//执行查询List<Customer> list = criteria.list();System.out.println(list);  //-------------------------------------------tx.commit();session.close();}

运行JUnit测试输出:

Hibernate: selectthis_.cust_id as cust_id1_0_0_,this_.cust_name as cust_nam2_0_0_,this_.cust_source as cust_sou3_0_0_,this_.cust_industry as cust_ind4_0_0_,this_.cust_level as cust_lev5_0_0_,this_.cust_linkman as cust_lin6_0_0_,this_.cust_phone as cust_pho7_0_0_,this_.cust_mobile as cust_mob8_0_0_ fromcst_customer this_ order bythis_.cust_id desc
[Customer [cust_id=5, cust_name=腾讯], Customer [cust_id=4, cust_name=阿里巴巴], Customer [cust_id=3, cust_name=百度], Customer [cust_id=2, cust_name=联想], Customer [cust_id=1, cust_name=Google]]
统计查询

条件查询需要调用criteria.setProjection()方法,参数为Projection对象。
Projections类的常用方法:作为查询容器的参数:

方法名称 描述 使用
Projections.avg 求平均值 Projections.avg(String propertyName)
Projections.count 统计某属性的数量 Projections.count(String propertyName)
Projections.countDistinct 统计某属性不同值的数量 Projections.countDistinct(String propertyName)
Projections.groupProperty 指定某个属性为分组属性 Projections.groupProperty(String propertyName)
Projections.max 求最大值 Projections.max(String propertyName)
Projections.min 求最小值 Projections.min(String propertyName)
Projections.projectionList 创建一个ProjectionList对象 Projections.projectionList()
Projections.rowCount 统计结果集中的记录条数 Projections.rowCount()
Projections.sum 求某属性的合计 Projections.sum(String propertyName)
@Test//查询总记录数public void fun5(){Session session = HibernateUtils.openSession();Transaction tx = session.beginTransaction();//-------------------------------------------//创建criteria查询对象Criteria criteria = session.createCriteria(Customer.class);//设置查询的聚合函数 => 总行数criteria.setProjection(Projections.rowCount());Long count = (Long) criteria.uniqueResult();System.out.println(count);//-------------------------------------------tx.commit();session.close();}

运行JUnit测试输出:

Hibernate: selectcount(*) as y0_ fromcst_customer this_
5

Hibernate--QBC举例+详解(一)相关推荐

  1. (转)Hibernate的配置详解

    http://blog.csdn.net/yerenyuan_pku/article/details/65041077 在<Hibernate快速入门>一文中,我有讲到Hibernate的 ...

  2. java web几百万分页_举例详解用Java实现web分页功能的方法

    举例详解用Java实现web分页功能的方法 发布于 2020-11-25| 复制链接 摘记: 分页问题是一个非常普遍的问题,开发者几乎都会遇到,这里不讨论具体如何分页,说明一下Web方式下分页的原理. ...

  3. Hibernate Criteria对象详解(条件查询)

    Hibernate Criteria对象详解 2014-9-1 16:21| 发布者: 传智特刊| 查看: 7290| 评论: 0 摘要: Hibernate框架是目前JavaEE软件开发的企业主流框 ...

  4. struts2+hibernate+spring配置详解

    #struts2+hibernate+spring配置详解 struts2+hibernate+spring配置详解 哎 ,当初一个人做好难,现在终于弄好了,希望自学这个的能少走些弯路. 以下是自己配 ...

  5. Java开源项目Hibernate包作用详解

    Java开源项目Hibernate包作用详解 本文引自:http://hi.baidu.com/nick6610/blog/item/70b58afa0d0eab9259ee90f7.html Jav ...

  6. Hibernate二级缓存详解(转)

    Hibernate二级缓存详解(转) 本文转载 http://www.blogjava.net/supercrsky/articles/238580.html 与Session相对的是,Session ...

  7. 数据库事务隔离级别举例详解

    目录 一.前言 1.1.4种事务隔离级别 1.2.3种读现象 二.举例说明 2.1.读未提交 2.2.读已提交 2.3.可重复读 2.4.串行化 一.前言 本文主要对4种事务隔离级别,具体举例说明各自 ...

  8. Java程序员从笨鸟到菜鸟之(七十九)细谈Spring(八)spring+hibernate整合基本详解

    由于spring和hibernate处于不同的层次,Spring关心的是业务逻辑之间的组合关系,Spring提供了对他们的强大的管理能力, 而Hibernate完成了OR的映射,使开发人员不用再去关心 ...

  9. Struts+Spring+Hibernate整合入门详解

    标签: strutshibernatespringbeanactionimport 2007-08-12 16:05 36280人阅读 评论(13) 收藏 举报 分类: STRUTS&SPRI ...

  10. hibernate.hbm.xml详解

    在Hibernate中,各表的映射文件-.hbm.xml可以通过工具生成,例如在使用MyEclipse开发时,它提供了自动生成映射文件的工具.配置文件的基本结构如下: Xml代码 1 <?xml ...

最新文章

  1. MyEclipse2017在线安装SVN
  2. PetShop之ASP.NET缓存
  3. 计算机网络系统集成策略实现摘要,计算机网络集成策略实现探析
  4. PowerDesigner使用教程 —— 概念数据模型
  5. Python实训day05am【正则表达式、网络爬虫】
  6. AWS 用户指南笔记
  7. 关于二叉堆(优先队列)的其他操作及其应用
  8. 计组之存储系统:4、双口RAM和多模块存储器(存取周期、双端口RAM、多体并行存储器、存储体)
  9. Spark实战电影点评系统(一)
  10. 计算机图书管理属于计算机应用中的,计算机在图书管理中应用探究.doc
  11. 鸿蒙os2.0怎么报名,我想问一下各位,怎么报名鸿蒙os2.0
  12. servlet之监听器
  13. Eclipse hibernate Tools下载
  14. 电阻电容电感PCB封装真实尺寸大小
  15. 用什么材料作电磁屏蔽呢?
  16. SQL Server忘记密码后成功重置密码的方法
  17. 菜哥学知识图谱(通过“基于医疗知识图谱的问答系统”)(三)(代码分析)
  18. 腾讯云通过公众号开通短信验证码
  19. 八大古都大排名(权威版)
  20. 2022杭电多校八 1011-Stormwind(贪心)

热门文章

  1. 重启计算机连线的标志是,win10右下角总出现一个小地球图标怎么办_win10电脑网络连接图标变成地球如何解决...
  2. C# —— 面向对象编程练习
  3. PHP json_encode float
  4. 火绒安全安装出现NSIS error
  5. c语言题查询答案,C语言习题级答案.docx
  6. 心灵成长的六个定律 (3) - By 武志红
  7. iPhone(IOS10)忘记了访问限制的密码该怎么办?
  8. 如何解决mathtype公式拉大word中行间距的问题
  9. Monthly expense(二分)
  10. 网络安全等级保护指南|网络安全等级保护测评周期需要多久