Hibernate 标准查询

hibernate 标准查询

hibernate 提供了操纵对象和相应的 rdbms 表中可用的数据的替代方法。其中最常用的一种方法是标准的 api,它允许你建立一个标准的可编程查询对象来应用过滤规则和逻辑条件。

hibernate session 接口提供了 createcriteria() 方法,可用于创建一个 criteria 对象,使当您的应用程序执行一个标准查询时返回一个持久化对象的类的实例。

以下是一个最简单的标准查询的例子,它只是简单地返回对应于员工类的每个对象:

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);

// to get records having salary more than 2000
cr.add(restrictions.gt("salary", 2000));

// to get records having salary less than 2000
cr.add(restrictions.lt("salary", 2000));

// to get records having fistname starting with zara
cr.add(restrictions.like("firstname", "zara%"));

// case sensitive form of the above restriction.
cr.add(restrictions.ilike("firstname", "zara%"));

// to get records having salary in between 1000 and 2000
cr.add(restrictions.between("salary", 1000, 2000));

// to check if the given property is null
cr.add(restrictions.isnull("salary"));

// to check if the given property is not null
cr.add(restrictions.isnotnull("salary"));

// to check if the given property is empty
cr.add(restrictions.isempty("salary"));

// to check if the given property is not empty
cr.add(restrictions.isnotempty("salary"));

你可以模仿以下示例,使用逻辑表达式创建 and 或 or 的条件组合:

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

criterion salary = restrictions.gt("salary", 2000);
criterion name = restrictions.ilike("firstnname","zara%");

// to get records matching with or condistions
logicalexpression orexp = restrictions.or(salary, name);
cr.add( orexp );

// to get records matching with and condistions
logicalexpression andexp = restrictions.and(salary, name);
cr.add( andexp );

list results = cr.list();

另外,上述所有的条件都可按之前的教程中解释的那样与 hql 直接使用。

 

分页使用标准

这里有两种分页标准接口方法:

序号 方法描述
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();

 

排序结果

标准 api 提供了 org.hibernate.criterion.order 类可以去根据你的一个对象的属性把你的排序结果集按升序或降序排列。这个例子演示了如何使用 order 类对结果集进行排序:

criteria cr = session.createcriteria(employee.class);
// to get records having salary more than 2000
cr.add(restrictions.gt("salary", 2000));

// to sort records in descening order
crit.addorder(order.desc("salary"));

// to sort records in ascending order
crit.addorder(order.asc("salary"));

list results = cr.list();

 

预测与聚合

标准 api 提供了 org.hibernate.criterion.projections 类可得到各属性值的平均值,最大值或最小值。projections 类与 restrictions 类相似,均提供了几个获取预测实例的静态工厂方法。

以下是几个例子,涵盖了不同的情况,可按要求进行使用:

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

// to get total row count.
cr.setprojection(projections.rowcount());

// to get average of a property.
cr.setprojection(projections.avg("salary"));

// to get distinct count of a property.
cr.setprojection(projections.countdistinct("firstname"));

// to get maximum of a property.
cr.setprojection(projections.max("salary"));

// to get minimum of a property.
cr.setprojection(projections.min("salary"));

// to get sum of a property.
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 对象:

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)
);

以下是映射文件:

<?xml version="1.0" encoding="utf-8"?>
<!doctype hibernate-mapping public
 "-//hibernate/hibernate mapping dtd//en"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
   <class name="employee" table="employee">
      <meta attribute="class-description">
         this class contains the employee detail.
      </meta>
      <id name="id" type="int" column="id">
         <generator class="native"/>
      </id>
      <property name="firstname" column="first_name" type="string"/>
      <property name="lastname" column="last_name" type="string"/>
      <property name="salary" column="salary" type="int"/>
   </class>
</hibernate-mapping>

最后,我们将用 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();

      /* add few employee records in database */
      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);

      /* list down all the employees */
      me.listemployees();

      /* print total employee's count */
      me.countemployee();

      /* print toatl salary */
      me.totalsalary();
   }
   /* method to create an employee in the database */
   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;
   }

   /* method to  read all the employees having salary more than 2000 */
   public void listemployees( ){
      session session = factory.opensession();
      transaction tx = null;
      try{
         tx = session.begintransaction();
         criteria cr = session.createcriteria(employee.class);
         // add restriction.
         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();
      }
   }
   /* method to print total number of records */
   public void countemployee(){
      session session = factory.opensession();
      transaction tx = null;
      try{
         tx = session.begintransaction();
         criteria cr = session.createcriteria(employee.class);

         // to get total row count.
         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();
      }
   }
  /* method to print sum of salaries */
   public void totalsalary(){
      session session = factory.opensession();
      transaction tx = null;
      try{
         tx = session.begintransaction();
         criteria cr = session.createcriteria(employee.class);

         // to get total salary.
         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();
      }
   }
}

 

编译和执行

这是编译并运行上述应用程序的步骤。确保你有适当的 pathclasspath,然后执行编译程序。

  • 按照在配置一章讲述的方法创建 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)
mysql>

下一节:hibernate 原生sql

hibernate 教程

相关文章