教程 > hibernate 教程 > 阅读:93

hibernate 条件(criteria)查询——迹忆客-ag捕鱼王app官网

hibernate 提供了操作对象以及 rdbms 表中可用数据的替代方法。 其中一种方法是 criteria api,它允许我们以编程方式构建条件查询对象,我们可以在其中应用过滤规则和逻辑条件。

hibernate session 接口提供了 createcriteria() 方法,该方法可用于创建 criteria 对象,该对象在应用程序执行条件查询时返回持久对象类的实例。

以下是条件查询的最简单示例之一,它将简单地返回与 employee 类对应的每个对象。

criteria cr = session.createcriteria(employee.class);
list results = cr.list();

条件限制

我们可以使用 criteria 对象可用的 add() 方法来为条件查询添加限制。 以下是添加限制以返回工资等于 2000 的记录的示例

criteria cr = session.createcriteria(employee.class);
cr.add(restrictions.eq("salary", 2000));
list results = cr.list();

以下是涵盖不同场景的更多示例,可根据要求使用

criteria cr = session.createcriteria(employee.class);
// 获取工资超过2000的记录
cr.add(restrictions.gt("salary", 2000));
// 获取工资低于 2000 的记录
cr.add(restrictions.lt("salary", 2000));
// 获取以 zara 开头的 firstname 的记录
cr.add(restrictions.like("firstname", "zara%"));
// 上述限制的区分大小写形式。
cr.add(restrictions.ilike("firstname", "zara%"));
// 获取工资在 1000 到 2000 之间的记录
cr.add(restrictions.between("salary", 1000, 2000));
// 检查给定属性是否为空
cr.add(restrictions.isnull("salary"));
// 检查给定属性是否不为空
cr.add(restrictions.isnotnull("salary"));
// 检查给定属性是否为空
cr.add(restrictions.isempty("salary"));
// 检查给定属性是否不为空
cr.add(restrictions.isnotempty("salary"));

我们可以使用 logicalexpression 限制创建 and 或 or 条件,如下所示

criteria cr = session.createcriteria(employee.class);
criterion salary = restrictions.gt("salary", 2000);
criterion name = restrictions.ilike("firstnname","zara%");
// 获取符合 or 条件的记录
logicalexpression orexp = restrictions.or(salary, name);
cr.add( orexp );
// 获取符合 and 条件的记录
logicalexpression andexp = restrictions.and(salary, name);
cr.add( andexp );
list results = cr.list();

尽管上述所有条件都可以直接与 hql 一起使用,如上一教程中所述。


使用标准分页

criteria 接口有两种分页方法。

序号 方法 描述
1 public criteria setfirstresult(int firstresult) 此方法采用一个整数,表示结果集中的第一行,从第 0 行开始。
2 public criteria setmaxresults(int maxresults) 此方法告诉 hibernate 检索固定数量的 maxresults 对象。

结合使用以上两种方法,我们可以在我们的 web 或 swing 应用程序中构建一个分页组件。 以下是示例,我们可以将其扩展为一次获取 10 行

criteria cr = session.createcriteria(employee.class);
cr.setfirstresult(1);
cr.setmaxresults(10);
list results = cr.list();

对结果进行排序

criteria api 提供了 org.hibernate.criterion.order 类,用于根据对象的属性之一来升序或降序对结果集进行排序。 此示例演示如何使用 order 类对结果集进行排序

criteria cr = session.createcriteria(employee.class);
// 获取工资超过2000的记录
cr.add(restrictions.gt("salary", 2000));
// 按降序对记录进行排序
cr.addorder(order.desc("salary"));
// 按升序对记录进行排序
cr.addorder(order.asc("salary"));
list results = cr.list();

预测和聚合

criteria api 提供 org.hibernate.criterion.projections 类,可用于获取属性值的平均值、最大值或最小值。 projections 类类似于 restrictions 类,因为它提供了几个静态工厂方法来获取 projection 实例。

以下是涵盖不同场景的几个示例,可根据需要使用

criteria cr = session.createcriteria(employee.class);
// 获取总行数。
cr.setprojection(projections.rowcount());
// 获取平均值
cr.setprojection(projections.avg("salary"));
// 获取属性的不同计数。
cr.setprojection(projections.countdistinct("firstname"));
// 获取属性的最大值
cr.setprojection(projections.max("salary"));
// 获取属性的最小值
cr.setprojection(projections.min("salary"));
// 获取总和
cr.setprojection(projections.sum("salary"));

条件查询示例

考虑以下 pojo 类

public class employee {
   private int id;
   private string firstname; 
   private string lastname;   
   private int salary;  
   public employee() {}
   
   public employee(string fname, string lname, int salary) {
      this.firstname = fname;
      this.lastname = lname;
      this.salary = salary;
   }
   
   public int getid() {
      return id;
   }
   
   public void setid( int id ) {
      this.id = id;
   }
   
   public string getfirstname() {
      return firstname;
   }
   
   public void setfirstname( string first_name ) {
      this.firstname = first_name;
   }
   
   public string getlastname() {
      return lastname;
   }
   
   public void setlastname( string last_name ) {
      this.lastname = last_name;
   }
   
   public int getsalary() {
      return salary;
   }
   
   public void setsalary( int salary ) {
      this.salary = salary;
   }
}

让我们创建以下 employee 表来存储 employee 对象

create table employee (
   id int not null auto_increment,
   first_name varchar(20) default null,
   last_name  varchar(20) default null,
   salary     int  default null,
   primary key (id)
);

以下是映射文件。


 

   
      
      
         this class contains the employee detail. 
      
      
      
         
      
      
      
      
      
      
   

最后,我们将使用 main() 方法创建我们的应用程序类来运行我们将使用 criteria 查询的应用程序

import java.util.list; 
import java.util.date;
import java.util.iterator; 
 
import org.hibernate.hibernateexception; 
import org.hibernate.session; 
import org.hibernate.transaction;
import org.hibernate.sessionfactory;
import org.hibernate.criteria;
import org.hibernate.criterion.restrictions;
import org.hibernate.criterion.projections;
import org.hibernate.cfg.configuration;
public class manageemployee {
   private static sessionfactory factory; 
   public static void main(string[] args) {
      
      try {
         factory = new configuration().configure().buildsessionfactory();
      } catch (throwable ex) { 
         system.err.println("failed to create sessionfactory object."   ex);
         throw new exceptionininitializererror(ex); 
      }
      
      manageemployee me = new manageemployee();
      /* 在数据库中添加一些员工记录 */
      integer empid1 = me.addemployee("zara", "ali", 2000);
      integer empid2 = me.addemployee("daisy", "das", 5000);
      integer empid3 = me.addemployee("john", "paul", 5000);
      integer empid4 = me.addemployee("mohd", "yasee", 3000);
      /* 列出所有员工 */
      me.listemployees();
      /* 打印员工总数 */
      me.countemployee();
      /* 打印薪资总数 */
      me.totalsalary();
   }
   
   /* 在数据库中创建员工的方法 */
   public integer addemployee(string fname, string lname, int salary){
      session session = factory.opensession();
      transaction tx = null;
      integer employeeid = null;
      
      try {
         tx = session.begintransaction();
         employee employee = new employee(fname, lname, salary);
         employeeid = (integer) session.save(employee); 
         tx.commit();
      } catch (hibernateexception e) {
         if (tx!=null) tx.rollback();
         e.printstacktrace(); 
      } finally {
         session.close(); 
      }
      return employeeid;
   }
   /* 读取所有工资超过 2000 的员工的方法 */
   public void listemployees( ) {
      session session = factory.opensession();
      transaction tx = null;
      
      try {
         tx = session.begintransaction();
         criteria cr = session.createcriteria(employee.class);
         // 添加限制
         cr.add(restrictions.gt("salary", 2000));
         list employees = cr.list();
         for (iterator iterator = employees.iterator(); iterator.hasnext();){
            employee employee = (employee) iterator.next(); 
            system.out.print("first name: "   employee.getfirstname()); 
            system.out.print("  last name: "   employee.getlastname()); 
            system.out.println("  salary: "   employee.getsalary()); 
         }
         tx.commit();
      } catch (hibernateexception e) {
         if (tx!=null) tx.rollback();
         e.printstacktrace(); 
      } finally {
         session.close(); 
      }
   }
   
   /* 打印总记录数的方法 */
   public void countemployee(){
      session session = factory.opensession();
      transaction tx = null;
      
      try {
         tx = session.begintransaction();
         criteria cr = session.createcriteria(employee.class);
         // 获取总行数。
         cr.setprojection(projections.rowcount());
         list rowcount = cr.list();
         system.out.println("total coint: "   rowcount.get(0) );
         tx.commit();
      } catch (hibernateexception e) {
         if (tx!=null) tx.rollback();
         e.printstacktrace(); 
      } finally {
         session.close(); 
      }
   }
  
   /* 打印工资总额的方法 */
   public void totalsalary(){
      session session = factory.opensession();
      transaction tx = null;
      
      try {
         tx = session.begintransaction();
         criteria cr = session.createcriteria(employee.class);
         // 获得总工资。
         cr.setprojection(projections.sum("salary"));
         list totalsalary = cr.list();
         system.out.println("total salary: "   totalsalary.get(0) );
         tx.commit();
      } catch (hibernateexception e) {
         if (tx!=null) tx.rollback();
         e.printstacktrace(); 
      } finally {
         session.close(); 
      }
   }
}

编译和执行

以下是编译和运行上述应用程序的步骤。 在继续编译和执行之前,请确保已正确设置 path 和 classpath。

  • 按照配置章节中的说明创建 hibernate.cfg.xml 配置文件。
  • 如上所示创建employee.hbm.xml 映射文件。
  • 如上所示创建employee.java 源文件并编译它。
  • 如上所示创建 manageemployee.java 源文件并编译它。
  • 执行 manageemployee 二进制文件来运行程序。

我们将获得以下结果,并且将在 employee 表中创建记录。

$ java manageemployee
.......various log messages will display here........
first name: daisy  last name: das  salary: 5000
first name: john  last name: paul  salary: 5000
first name: mohd  last name: yasee  salary: 3000
total coint: 4
total salary: 15000

如果检查自己的 employee 表,它应该有以下记录

mysql> select * from employee;
 ---- ------------ ----------- -------- 
| id | first_name | last_name | salary |
 ---- ------------ ----------- -------- 
| 14 | zara       | ali       |   2000 |
| 15 | daisy      | das       |   5000 |
| 16 | john       | paul      |   5000 |
| 17 | mohd       | yasee     |   3000 |
 ---- ------------ ----------- -------- 
4 rows in set (0.00 sec)

查看笔记

扫码一下
查看教程更方便
网站地图