标准查询

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

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

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

  1. Criteria cr = session.createCriteria(Employee.class);
  2. List results = cr.list();

对标准的限制

你可以使用 Criteria 对象可用的 add() 方法去添加一个标准查询的限制。

以下是一个示例,它实现了添加一个限制,令返回工资等于 2000 的记录:

  1. Criteria cr = session.createCriteria(Employee.class);
  2. cr.add(Restrictions.eq("salary", 2000));
  3. List results = cr.list();

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

  1. Criteria cr = session.createCriteria(Employee.class);
  2. // To get records having salary more than 2000
  3. cr.add(Restrictions.gt("salary", 2000));
  4. // To get records having salary less than 2000
  5. cr.add(Restrictions.lt("salary", 2000));
  6. // To get records having fistName starting with zara
  7. cr.add(Restrictions.like("firstName", "zara%"));
  8. // Case sensitive form of the above restriction.
  9. cr.add(Restrictions.ilike("firstName", "zara%"));
  10. // To get records having salary in between 1000 and 2000
  11. cr.add(Restrictions.between("salary", 1000, 2000));
  12. // To check if the given property is null
  13. cr.add(Restrictions.isNull("salary"));
  14. // To check if the given property is not null
  15. cr.add(Restrictions.isNotNull("salary"));
  16. // To check if the given property is empty
  17. cr.add(Restrictions.isEmpty("salary"));
  18. // To check if the given property is not empty
  19. cr.add(Restrictions.isNotEmpty("salary"));

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

  1. Criteria cr = session.createCriteria(Employee.class);
  2. Criterion salary = Restrictions.gt("salary", 2000);
  3. Criterion name = Restrictions.ilike("firstNname","zara%");
  4. // To get records matching with OR condistions
  5. LogicalExpression orExp = Restrictions.or(salary, name);
  6. cr.add( orExp );
  7. // To get records matching with AND condistions
  8. LogicalExpression andExp = Restrictions.and(salary, name);
  9. cr.add( andExp );
  10. List results = cr.list();

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

分页使用标准

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

序号 方法描述
1 public Criteria setFirstResult(int firstResult),这种方法需要一个代表你的结果集的第一行的整数,以第 0 行为开始。
2 public Criteria setMaxResults(int maxResults),这个方法设置了 Hibernate 检索对象的 maxResults

利用上述两种方法结合在一起,我们可以在我们的 Web 或 Swing 应用程序构建一个分页组件。以下是一个例子,利用它你可以一次取出 10 行:

  1. Criteria cr = session.createCriteria(Employee.class);
  2. cr.setFirstResult(1);
  3. cr.setMaxResults(10);
  4. List results = cr.list();

排序结果

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

  1. Criteria cr = session.createCriteria(Employee.class);
  2. // To get records having salary more than 2000
  3. cr.add(Restrictions.gt("salary", 2000));
  4. // To sort records in descening order
  5. crit.addOrder(Order.desc("salary"));
  6. // To sort records in ascending order
  7. crit.addOrder(Order.asc("salary"));
  8. List results = cr.list();

预测与聚合

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

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

  1. Criteria cr = session.createCriteria(Employee.class);
  2. // To get total row count.
  3. cr.setProjection(Projections.rowCount());
  4. // To get average of a property.
  5. cr.setProjection(Projections.avg("salary"));
  6. // To get distinct count of a property.
  7. cr.setProjection(Projections.countDistinct("firstName"));
  8. // To get maximum of a property.
  9. cr.setProjection(Projections.max("salary"));
  10. // To get minimum of a property.
  11. cr.setProjection(Projections.min("salary"));
  12. // To get sum of a property.
  13. cr.setProjection(Projections.sum("salary"));

标准查询示例

考虑下面的 POJO 类:

  1. public class Employee {
  2. private int id;
  3. private String firstName;
  4. private String lastName;
  5. private int salary;
  6. public Employee() {}
  7. public Employee(String fname, String lname, int salary) {
  8. this.firstName = fname;
  9. this.lastName = lname;
  10. this.salary = salary;
  11. }
  12. public int getId() {
  13. return id;
  14. }
  15. public void setId( int id ) {
  16. this.id = id;
  17. }
  18. public String getFirstName() {
  19. return firstName;
  20. }
  21. public void setFirstName( String first_name ) {
  22. this.firstName = first_name;
  23. }
  24. public String getLastName() {
  25. return lastName;
  26. }
  27. public void setLastName( String last_name ) {
  28. this.lastName = last_name;
  29. }
  30. public int getSalary() {
  31. return salary;
  32. }
  33. public void setSalary( int salary ) {
  34. this.salary = salary;
  35. }
  36. }

让我们创建以下员工表来存储 Employee 对象:

  1. create table EMPLOYEE (
  2. id INT NOT NULL auto_increment,
  3. first_name VARCHAR(20) default NULL,
  4. last_name VARCHAR(20) default NULL,
  5. salary INT default NULL,
  6. PRIMARY KEY (id)
  7. );

以下是映射文件:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <!DOCTYPE hibernate-mapping PUBLIC
  3. "-//Hibernate/Hibernate Mapping DTD//EN"
  4. "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
  5. <hibernate-mapping>
  6. <class name="Employee" table="EMPLOYEE">
  7. <meta attribute="class-description">
  8. This class contains the employee detail.
  9. </meta>
  10. <id name="id" type="int" column="id">
  11. <generator class="native"/>
  12. </id>
  13. <property name="firstName" column="first_name" type="string"/>
  14. <property name="lastName" column="last_name" type="string"/>
  15. <property name="salary" column="salary" type="int"/>
  16. </class>
  17. </hibernate-mapping>

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

  1. import java.util.List;
  2. import java.util.Date;
  3. import java.util.Iterator;
  4. import org.hibernate.HibernateException;
  5. import org.hibernate.Session;
  6. import org.hibernate.Transaction;
  7. import org.hibernate.SessionFactory;
  8. import org.hibernate.Criteria;
  9. import org.hibernate.criterion.Restrictions;
  10. import org.hibernate.criterion.Projections;
  11. import org.hibernate.cfg.Configuration;
  12. public class ManageEmployee {
  13. private static SessionFactory factory;
  14. public static void main(String[] args) {
  15. try{
  16. factory = new Configuration().configure().buildSessionFactory();
  17. }catch (Throwable ex) {
  18. System.err.println("Failed to create sessionFactory object." + ex);
  19. throw new ExceptionInInitializerError(ex);
  20. }
  21. ManageEmployee ME = new ManageEmployee();
  22. /* Add few employee records in database */
  23. Integer empID1 = ME.addEmployee("Zara", "Ali", 2000);
  24. Integer empID2 = ME.addEmployee("Daisy", "Das", 5000);
  25. Integer empID3 = ME.addEmployee("John", "Paul", 5000);
  26. Integer empID4 = ME.addEmployee("Mohd", "Yasee", 3000);
  27. /* List down all the employees */
  28. ME.listEmployees();
  29. /* Print Total employee's count */
  30. ME.countEmployee();
  31. /* Print Toatl salary */
  32. ME.totalSalary();
  33. }
  34. /* Method to CREATE an employee in the database */
  35. public Integer addEmployee(String fname, String lname, int salary){
  36. Session session = factory.openSession();
  37. Transaction tx = null;
  38. Integer employeeID = null;
  39. try{
  40. tx = session.beginTransaction();
  41. Employee employee = new Employee(fname, lname, salary);
  42. employeeID = (Integer) session.save(employee);
  43. tx.commit();
  44. }catch (HibernateException e) {
  45. if (tx!=null) tx.rollback();
  46. e.printStackTrace();
  47. }finally {
  48. session.close();
  49. }
  50. return employeeID;
  51. }
  52. /* Method to READ all the employees having salary more than 2000 */
  53. public void listEmployees( ){
  54. Session session = factory.openSession();
  55. Transaction tx = null;
  56. try{
  57. tx = session.beginTransaction();
  58. Criteria cr = session.createCriteria(Employee.class);
  59. // Add restriction.
  60. cr.add(Restrictions.gt("salary", 2000));
  61. List employees = cr.list();
  62. for (Iterator iterator =
  63. employees.iterator(); iterator.hasNext();){
  64. Employee employee = (Employee) iterator.next();
  65. System.out.print("First Name: " + employee.getFirstName());
  66. System.out.print(" Last Name: " + employee.getLastName());
  67. System.out.println(" Salary: " + employee.getSalary());
  68. }
  69. tx.commit();
  70. }catch (HibernateException e) {
  71. if (tx!=null) tx.rollback();
  72. e.printStackTrace();
  73. }finally {
  74. session.close();
  75. }
  76. }
  77. /* Method to print total number of records */
  78. public void countEmployee(){
  79. Session session = factory.openSession();
  80. Transaction tx = null;
  81. try{
  82. tx = session.beginTransaction();
  83. Criteria cr = session.createCriteria(Employee.class);
  84. // To get total row count.
  85. cr.setProjection(Projections.rowCount());
  86. List rowCount = cr.list();
  87. System.out.println("Total Coint: " + rowCount.get(0) );
  88. tx.commit();
  89. }catch (HibernateException e) {
  90. if (tx!=null) tx.rollback();
  91. e.printStackTrace();
  92. }finally {
  93. session.close();
  94. }
  95. }
  96. /* Method to print sum of salaries */
  97. public void totalSalary(){
  98. Session session = factory.openSession();
  99. Transaction tx = null;
  100. try{
  101. tx = session.beginTransaction();
  102. Criteria cr = session.createCriteria(Employee.class);
  103. // To get total salary.
  104. cr.setProjection(Projections.sum("salary"));
  105. List totalSalary = cr.list();
  106. System.out.println("Total Salary: " + totalSalary.get(0) );
  107. tx.commit();
  108. }catch (HibernateException e) {
  109. if (tx!=null) tx.rollback();
  110. e.printStackTrace();
  111. }finally {
  112. session.close();
  113. }
  114. }
  115. }

编译和执行

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

  • 按照在配置一章讲述的方法创建 hibernate.cfg.xml 配置文件。
  • 如上述所示创建 employee.hbm.xml 映射文件。
  • 如上述所示创建 employee.java 源文件并编译。
  • 如上述所示创建 manageemployee.java 源文件并编译。
  • 执行 manageemployee 二进制代码运行程序。

你会得到下面的结果,并且记录将会在 EMPLOYEE 表创建。

  1. $java ManageEmployee
  2. .......VARIOUS LOG MESSAGES WILL DISPLAY HERE........
  3. First Name: Daisy Last Name: Das Salary: 5000
  4. First Name: John Last Name: Paul Salary: 5000
  5. First Name: Mohd Last Name: Yasee Salary: 3000
  6. Total Coint: 4
  7. Total Salary: 15000

如果你检查你的 EMPLOYEE 表,它应该有以下记录:

  1. mysql> select * from EMPLOYEE;
  2. +----+------------+-----------+--------+
  3. | id | first_name | last_name | salary |
  4. +----+------------+-----------+--------+
  5. | 14 | Zara | Ali | 2000 |
  6. | 15 | Daisy | Das | 5000 |
  7. | 16 | John | Paul | 5000 |
  8. | 17 | Mohd | Yasee | 3000 |
  9. +----+------------+-----------+--------+
  10. 4 rows in set (0.00 sec)
  11. mysql>