• Hibernate 查询语句


    Hibernate查询语言(HQL)是一种面向对象的查询语言,类似于SQL,但不是对表和列操作,HQL适用于持久对象和它们的属性。 HQL查询由Hibernate转换成传统的SQL查询,这在圈上的数据库执行操作。

    虽然可以直接使用SQL语句和Hibernate使用原生SQL,但建议使用HQL尽可能避免数据库可移植性的麻烦,并采取Hibernate的SQL生成和缓存策略的优势。

    都像SELECT,FROM和WHERE等关键字不区分大小写,但如表名和列名的属性是区分在HQL敏感。

    FROM 语句
    使用FROM子句,如果要加载一个完整的持久化对象到内存中。下面是一个使用FROM子句的简单的语法:

    1 String hql = "FROM Employee";//Employee 是实体类名,严格区分大小写
    2 Query query = session.createQuery(hql);
    3 List results = query.list();

    如果需要完全限定在HQL一个类名,只需指定如下的包和类名:

    1 String hql = "FROM com.shuyinghengxie.haha.Employee";
    2 Query query = session.createQuery(hql);
    3 List results = query.list();

    AS 语句
    AS子句可以用来别名分配给类中的HQL查询,特别是当有很长的查询。例如,我们前面简单的例子是以下几点:

    String hql = "FROM Employee AS E";
    Query query = session.createQuery(hql);
    List results = query.list();

    AS关键字是可选的,也可以直接在之后的类名指定别名,如下所示:

    1 String hql = "FROM Employee E";
    2 Query query = session.createQuery(hql);
    3 List results = query.list();

    SELECT 子句
    SELECT子句提供了更多的控制权比from子句的结果集。如果想获得对象而不是整个对象的几个属性,使用SELECT子句。下面是一个使用SELECT语句来获取Employee对象只是FIRST_NAME字段的简单的语法:

    String hql = "SELECT E.firstName FROM Employee E";
    Query query = session.createQuery(hql);
    List results = query.list();

    值得注意的是在这里,Employee.firstName是Employee对象的一个属性,而不是EMPLOYEE表的一个字段。

    WHERE 子句
    如果想缩小了从存储返回的特定对象,可以使用WHERE子句。下面是一个使用WHERE子句的简单的语法:

    String hql = "FROM Employee E WHERE E.id = 10";
    Query query = session.createQuery(hql);
    List results = query.list();

    ORDER BY 子句
    若要排序HQL查询的结果,将需要使用ORDER BY子句。您可以在结果集按升序(ASC)或降序(DESC)通过在对象的任何属性排序结果。下面是一个使用ORDER BY子句的简单的语法:

    String hql = "FROM Employee E WHERE E.id > 10 ORDER BY E.salary DESC";
    Query query = session.createQuery(hql);
    List results = query.list();

    如果想通过一个以上的属性进行排序,你会仅仅是额外的属性添加到由子句用逗号隔开,如下所示的命令的结尾:

    String hql = "FROM Employee E WHERE E.id > 10 " +
           "ORDER BY E.firstName DESC, E.salary DESC ";
    Query query = session.createQuery(hql);
    List results = query.list();

    GROUP BY 子句
    该子句允许从Hibernate的它基于属性的值的数据库和组提取信息,并且通常使用结果包括总值。下面是一个使用GROUP BY子句的语法很简单:

    String hql = "SELECT SUM(E.salary), E.firtName FROM Employee E " +
           "GROUP BY E.firstName";
    Query query = session.createQuery(hql);
    List results = query.list();

    使用命名参数
    Hibernate命名在其HQL查询参数支持。这使得编写接受来自用户的输入容易,不必对SQL注入攻击防御HQL查询。下面是一个使用命名参数的简单的语法:

    String hql = "FROM Employee E WHERE E.id = :employee_id";
    Query query = session.createQuery(hql);
    query.setParameter("employee_id",10);
    List results = query.list();

    UPDATE 子句
    批量更新是新的HQL与Hibernate3,以及不同的删除工作,在Hibernate 3和Hibernate2一样。 Query接口现在包含一个名为executeUpdate()方法用于执行HQL UPDATE或DELETE语句。

    在UPDATE子句可以用于更新一个或多个对象中的一个或多个属性。下面是一个使用UPDATE子句的简单的语法:

    1 String hql = "UPDATE Employee set salary = :salary " + 
    2        "WHERE id = :employee_id";
    3 Query query = session.createQuery(hql);
    4 query.setParameter("salary", 1000);
    5 query.setParameter("employee_id", 10);
    6 int result = query.executeUpdate();
    7 System.out.println("Rows affected: " + result);

    DELETE 子句
    DELETE子句可以用来删除一个或多个对象。下面是一个使用DELETE子句的简单的语法:

    1 String hql = "DELETE FROM Employee " + 
    2        "WHERE id = :employee_id";
    3 Query query = session.createQuery(hql);
    4 query.setParameter("employee_id", 10);
    5 int result = query.executeUpdate();
    6 System.out.println("Rows affected: " + result);

    INSERT 子句
    HQL支持INSERT INTO子句中只记录在那里可以插入从一个对象到另一个对象。以下是使用INSERT INTO子句的简单的语法:

    String hql = "INSERT INTO Employee(firstName, lastName, salary)" + 
           "SELECT firstName, lastName, salary FROM old_employee";
    Query query = session.createQuery(hql);
    int result = query.executeUpdate();
    System.out.println("Rows affected: " + result);

     聚合方法
    HQL支持多种聚合方法,类似于SQL。他们工作在HQL同样的方式在SQL和下面的可用功能列表:

    DISTINCT关键字只计算在该行设定的唯一值。下面的查询将只返回唯一的计数:

    1 String hql = "SELECT count(distinct E.firstName) FROM Employee E";
    2 Query query = session.createQuery(hql);
    3 List results = query.list();

    使用查询分页
    有用于分页查询接口的两个方法。

    • Query setFirstResult(int startPosition)
    • Query setMaxResults(int maxResult)

    采用上述两种方法一起,可以在网站或Swing应用程序构建一个分页组件。下面是例子,可以扩展来获取10行:

    1 String hql = "FROM Employee";
    2 Query query = session.createQuery(hql);
    3 query.setFirstResult(1);
    4 query.setMaxResults(10);
    5 List results = query.list();

    查询条件
    Hibernate提供了操作对象,并依次数据在RDBMS表可用的备用方式。其中一个方法是标准的API,它允许你建立一个标准的查询对象编程,可以套用过滤规则和逻辑条件。
    Hibernate的Session接口提供了可用于创建一个返回的持久化对象的类的实例时,应用程序执行一个条件查询一个Criteria对象createCriteria()方法。

    以下是最简单的一个条件查询的例子是将简单地返回对应于Employee类的每个对象。

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

    限制与标准:
    可以使用add()方法可用于Criteria对象添加限制条件查询。下面是例子增加一个限制与薪水返回的记录是等于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  
     3 // To get records having salary more than 2000
     4 cr.add(Restrictions.gt("salary", 2000));
     5  
     6 // To get records having salary less than 2000
     7 cr.add(Restrictions.lt("salary", 2000));
     8  
     9 // To get records having fistName starting with zara
    10 cr.add(Restrictions.like("firstName", "zara%"));
    11  
    12 // Case sensitive form of the above restriction.
    13 cr.add(Restrictions.ilike("firstName", "zara%"));
    14  
    15 // To get records having salary in between 1000 and 2000
    16 cr.add(Restrictions.between("salary", 1000, 2000));
    17  
    18 // To check if the given property is null
    19 cr.add(Restrictions.isNull("salary"));
    20  
    21 // To check if the given property is not null
    22 cr.add(Restrictions.isNotNull("salary"));
    23  
    24 // To check if the given property is empty
    25 cr.add(Restrictions.isEmpty("salary"));
    26  
    27 // To check if the given property is not empty
    28 cr.add(Restrictions.isNotEmpty("salary"));
    29 可以创建AND或OR使用LogicalExpression限制如下条件:
    30  
    31 Criteria cr = session.createCriteria(Employee.class);
    32  
    33 Criterion salary = Restrictions.gt("salary", 2000);
    34 Criterion name = Restrictions.ilike("firstNname","zara%");
    35  
    36 // To get records matching with OR condistions
    37 LogicalExpression orExp = Restrictions.or(salary, name);
    38 cr.add( orExp );
    39  
    40  
    41 // To get records matching with AND condistions
    42 LogicalExpression andExp = Restrictions.and(salary, name);
    43 cr.add( andExp );
    44  
    45 List results = cr.list();

    虽然上述所有条件,可以直接使用HQL在前面的教程中介绍。

    分页使用标准:
    还有的标准接口,用于分页的两种方法。

    • public Criteria setFirstResult(int firstResult)
    • public Criteria setMaxResults(int maxResults)

    采用上述两种方法一起,我们可以在我们的网站或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  
     5 // To sort records in descening order
     6 crit.addOrder(Order.desc("salary"));
     7  
     8 // To sort records in ascending order
     9 crit.addOrder(Order.asc("salary"));
    10  
    11 List results = cr.list();

    预测与聚合:
    该Criteria API提供了一个org.hibernate.criterion.Projections类可用于获取平均值,最大值或最小值的属性值。Projections类是类似于类限制,因为它提供了几个静态工厂方法用于获得Projection 实例。  provides the

    以下是涉及不同的方案的一些例子,可按规定使用:

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

    Criteria Queries 例子:
    考虑下面的POJO类:

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

    让我们创建下面的EMPLOYEE表来存储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  
     6 <hibernate-mapping>
     7   <class name="Employee" table="EMPLOYEE">
     8    <meta attribute="class-description">
     9      This class contains the employee detail. 
    10    </meta>
    11    <id name="id" type="int" column="id">
    12      <generator class="native"/>
    13    </id>
    14    <property name="firstName" column="first_name" type="string"/>
    15    <property name="lastName" column="last_name" type="string"/>
    16    <property name="salary" column="salary" type="int"/>
    17   </class>
    18 </hibernate-mapping>

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

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

    编译和执行:
    下面是步骤来编译并运行上述应用程序。请确保您已在进行的编译和执行之前,适当地设置PATH和CLASSPATH。

    • 创建hibernate.cfg.xml配置文件中配置章节解释。
    • 创建Employee.hbm.xml映射文件,如上图所示。
    • 创建Employee.java源文件,如上图所示,并编译它。
    • 创建ManageEmployee.java源文件,如上图所示,并编译它。
    • 执行ManageEmployee二进制运行程序.

    会得到以下结果,并记录将创建在EMPLOYEE表中。

    转自http://www.jb51.net/article/76764.htm 

  • 相关阅读:
    团队第二次作业
    重载和多态
    团队第一次作业
    结对编程
    java处理数字字符串每5个数字为一组进行拆分,保留逗号。不足5个的也存为一组。
    POI & easyExcel快速使用
    Access denied for user 'root'@'localhost' (using password: YES) 解决方法
    快速理解 并发,并行,同步,异步
    Spring Tools Suite 安装于基本使用
    Mysql 数据备份与恢复
  • 原文地址:https://www.cnblogs.com/20gg-com/p/6045739.html
Copyright © 2020-2023  润新知