标准查询

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

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

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

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

    1. cr.add(Restrictions.eq("salary", 2000));
    2. 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"));
    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 直接使用。

    分页使用标准

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

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

    标准 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.salary = salary;
    10. }
    11. return id;
    12. }
    13. public void setId( int id ) {
    14. this.id = id;
    15. }
    16. public String getFirstName() {
    17. return firstName;
    18. }
    19. public void setFirstName( String first_name ) {
    20. this.firstName = first_name;
    21. }
    22. public String getLastName() {
    23. return lastName;
    24. }
    25. public void setLastName( String last_name ) {
    26. this.lastName = last_name;
    27. }
    28. public int getSalary() {
    29. return salary;
    30. }
    31. public void setSalary( int salary ) {
    32. this.salary = salary;
    33. }
    34. }

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

    以下是映射文件:

    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. employeeID = (Integer) session.save(employee);
    41. tx.commit();
    42. }catch (HibernateException e) {
    43. if (tx!=null) tx.rollback();
    44. e.printStackTrace();
    45. }finally {
    46. session.close();
    47. }
    48. return employeeID;
    49. }
    50. /* Method to READ all the employees having salary more than 2000 */
    51. public void listEmployees( ){
    52. Session session = factory.openSession();
    53. Transaction tx = null;
    54. try{
    55. tx = session.beginTransaction();
    56. Criteria cr = session.createCriteria(Employee.class);
    57. // Add restriction.
    58. cr.add(Restrictions.gt("salary", 2000));
    59. List employees = cr.list();
    60. for (Iterator iterator =
    61. employees.iterator(); iterator.hasNext();){
    62. Employee employee = (Employee) iterator.next();
    63. System.out.print("First Name: " + employee.getFirstName());
    64. System.out.print(" Last Name: " + employee.getLastName());
    65. System.out.println(" Salary: " + employee.getSalary());
    66. }
    67. tx.commit();
    68. }catch (HibernateException e) {
    69. if (tx!=null) tx.rollback();
    70. e.printStackTrace();
    71. }finally {
    72. session.close();
    73. }
    74. }
    75. /* Method to print total number of records */
    76. public void countEmployee(){
    77. Session session = factory.openSession();
    78. Transaction tx = null;
    79. try{
    80. tx = session.beginTransaction();
    81. Criteria cr = session.createCriteria(Employee.class);
    82. // To get total row count.
    83. cr.setProjection(Projections.rowCount());
    84. List rowCount = cr.list();
    85. System.out.println("Total Coint: " + rowCount.get(0) );
    86. tx.commit();
    87. }catch (HibernateException e) {
    88. if (tx!=null) tx.rollback();
    89. e.printStackTrace();
    90. }finally {
    91. session.close();
    92. }
    93. }
    94. /* Method to print sum of salaries */
    95. public void totalSalary(){
    96. Session session = factory.openSession();
    97. Transaction tx = null;
    98. try{
    99. tx = session.beginTransaction();
    100. Criteria cr = session.createCriteria(Employee.class);
    101. // To get total salary.
    102. cr.setProjection(Projections.sum("salary"));
    103. List totalSalary = cr.list();
    104. System.out.println("Total Salary: " + totalSalary.get(0) );
    105. tx.commit();
    106. }catch (HibernateException e) {
    107. if (tx!=null) tx.rollback();
    108. e.printStackTrace();
    109. }finally {
    110. session.close();
    111. }
    112. }
    113. }

    编译和执行

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

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

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