Hibernate-HQL、Criteria、SQL实现查询对照以及增删改

来源:互联网 发布:cad迷你看图mac版免费 编辑:程序博客网 时间:2024/06/05 09:43

本文旨在为读者呈现不同的方式查询方式:HQL方式的查询、SQL原生态SQL方式的查询、以及Criteria方式的查询,拓展查询的不同实现思路,开阔视野、并涵盖了部分的Hibernate增删改的基本操作。

简单介绍一下HQL和Criteria:

HQL

HQL(Hibernate Query Language)提供更加丰富灵活、更为强大的查询能力;HQL更接近SQL语句查询语法;
[select/delete/update…][from…][where…][group by…][having…][order by…]

Criteria

      Criteria是一种比hql面向对象的查询方式。Criteria 可使用 Criterion 和 Projection 设置查询条件。可以设置 FetchMode(联合查询抓取的模式 ) ,设置排序方式,Criteria 还可以设置 FlushModel (冲刷 Session 的方式)和 LockModeCriterion 是 Criteria 的查询条件。
      Criteria 提供了 add(Criterion criterion) 方法来添加查询条件。Criterion 接口的主要实现包括: Example 、 Junction 和 SimpleExpression 。而Junction 的实际使用是它的两个子类 conjunction 和 disjunction ,分别是使用 AND 和 OR 操作符进行来联结查询条件集合。

Criterion 的实例可以通过 Restrictions 工具类来创建,Restrictions 提供了大量的静态方法,如 eq (等于)、 ge (大于等于)、 between 等来方法的创建 Criterion 查询条件(SimpleExpression 实例)。除此之外, Restrictions 还提供了方法来创建 conjunction 和disjunction 实例,通过往该实例的 add(Criteria) 方法来增加查询条件形成一个查询条件集合。
Example 的创建有所不同, Example 本身提供了一个静态方法 create(Objectentity) ,即根据一个对象(实际使用中一般是映射到数据库的对象)来创建。然后可以设置一些过滤条件:
Example exampleUser =Example.create(u)
.ignoreCase() // 忽略大小写
.enableLike(MatchMode.ANYWHERE); // 对 String 类型的属性,无论在那里值在那里都匹配。相当于 %value%
Project 主要是让 Criteria 能够进行报表查询,并可以实现分组。 Project 主要有SimpleProjection 、ProjectionList 和 Property 三个实现。其中SimpleProjection 和ProjectionList 的实例化是由内建的Projections 来完成,如提供的 avg 、count 、max 、min 、sum 可以让开发者很容易对某个字段进行统计查询。
Property 是对某个字段进行查询条件的设置,如通过Porperty.forName(“color”). in(new String[]{“black”,”red”,”write”}); 则可以创建一个 Project 实例。通过criteria 的 add(Project) 方法加入到查询条件中去。

准备工作

jar包以及项目的结构


User.java
[java] view plain copy
  1. package com.siti.domain;  
  2.   
  3. public class User {  
  4.   
  5.     private Long userId;  
  6.     private String userName;  
  7.     private String password;  
  8.       
  9.     public Long getUserId() {  
  10.         return userId;  
  11.     }  
  12.     public void setUserId(Long userId) {  
  13.         this.userId = userId;  
  14.     }  
  15.     public String getUserName() {  
  16.         return userName;  
  17.     }  
  18.     public void setUserName(String userName) {  
  19.         this.userName = userName;  
  20.     }  
  21.     public String getPassword() {  
  22.         return password;  
  23.     }  
  24.     public void setPassword(String password) {  
  25.         this.password = password;  
  26.     }  
  27.     @Override  
  28.     public String toString() {  
  29.         return "User [userId=" + userId + ", userName=" + userName  
  30.                 + ", password=" + password + "]";  
  31.     }  
  32.       
  33. }  

User.hbm.xml
[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC  
  3.                             "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  4.                             "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >  
  5. <hibernate-mapping package="com.siti.domain">  
  6.     <class name = "User" table="user">  
  7.         <id name = "userId" type = "java.lang.Long" column = "id">  
  8.             <generator class="native"></generator>  
  9.         </id>  
  10.         <property name="userName" type = "string" column = "userName" length = "20"></property>  
  11.         <property name="password" type = "string" column = "password"  length = "20"></property>  
  12.     </class>  
  13. </hibernate-mapping>  

hibernate.cfg.xml
[html] view plain copy
  1. <!DOCTYPE hibernate-configuration PUBLIC  
  2.     "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
  3.     "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">  
  4.   
  5. <!-- Generated by MyEclipse Hibernate Tools.                   -->  
  6. <hibernate-configuration>  
  7. <session-factory>  
  8.     <property name="hibernate.connection.driver_class">  
  9.         com.mysql.jdbc.Driver  
  10.     </property>  
  11.     <property name="hibernate.connection.url">  
  12.         jdbc:mysql://localhost:3306/hiber  
  13.     </property>  
  14.     <property name="hibernate.connection.username">root</property>  
  15.     <property name="hibernate.connection.password">root</property>  
  16.     <property name="dialect">  
  17.         org.hibernate.dialect.MySQLDialect  
  18.     </property>  
  19.     <property name="connection.pool_size">1</property>  
  20.     <property name="show_sql">true</property>  
  21.     <property name="hibernate.hbm2ddl.auto">update</property>  
  22.     <mapping resource="com/siti/domain/User.hbm.xml" />  
  23. </session-factory>  
  24.   
  25. </hibernate-configuration>  

对照代码

[java] view plain copy
  1. package com.siti.test;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.hibernate.SQLQuery;  
  6. import org.hibernate.Session;  
  7. import org.hibernate.SessionFactory;  
  8. import org.hibernate.cfg.Configuration;  
  9. import org.hibernate.criterion.Criterion;  
  10. import org.hibernate.criterion.Projection;  
  11. import org.hibernate.criterion.Projections;  
  12. import org.hibernate.criterion.Restrictions;  
  13.   
  14. import com.siti.domain.User;  
  15.   
  16. public class HiberTest {  
  17.   
  18.     static SessionFactory sessionFactory = null;  
  19.     static {  
  20.         sessionFactory = new Configuration()  
  21.         .configure()  
  22.         .buildSessionFactory();  
  23.     }  
  24.     public static void main(String[] args) {  
  25.       
  26.         testCriteriaSelectProjectUser();  
  27.     }  
  28.       
  29.     /** 
  30.      * 7. Criteria 方式投影分组查询 
  31.      * Hibernate: select this_.userName as y0_, count(this_.password) as y1_ from user this_ group by this_.userName 
  32.      *  
  33.      * [[Ljava.lang.Object;@1f44ec7, [Ljava.lang.Object;@602b6b, [Ljava.lang.Object;@1c297a3, [Ljava.lang.Object;@717323, [Ljava.lang.Object;@3e1bc8] 
  34.      *  
  35.      * 从这几个例子我们不难发现,如果没有指定select语句(没有投影),那么将返回表中的所有字段,返回结果会被封装到Entity实体对象User中,一但提供select语句(投影)后, 
  36.      * 返回的结果类型,将不再封装到User对象,而是根据投影的实际类型返回,这就是投影对结果封装策略的影响。  
  37.      */  
  38.     public static void testCriteriaSelectProjectUser(){  
  39.         Session session = sessionFactory.openSession();  
  40.         List<Object> userList = session.createCriteria(User.class)//  
  41.                 .setProjection(  
  42.                         Projections.projectionList()  
  43.                         .add(Projections.groupProperty("userName"))  
  44.                         .add(Projections.count("password"))  
  45.                     )  
  46.                 .list();  
  47.         System.out.println(userList);  
  48.         session.close();  
  49.     }  
  50.       
  51.       
  52.     /** 
  53.      * 6. SQL 方式测试查询附加条件id>? 
  54.      * Hibernate: select * from user where id > 5 // 注意这里用的是id>5而不是userId 
  55.      *  
  56.      * [User [userId=11, userName=zhangsan, password=zs]] 
  57.      *  
  58.      */  
  59.     public static void testSQLSelectUser(){  
  60.         Session session = sessionFactory.openSession();  
  61.         List<User> userList = session.createSQLQuery("select * from user where id > 5")//  
  62.                 .addEntity(User.class)//  
  63.                 .list();  
  64.         System.out.println(userList);  
  65.         session.close();  
  66.     }  
  67.     /** 
  68.      * 6. HQL 方式测试查询附加条件id>? 
  69.      * Hibernate: select user0_.id as id0_, user0_.userName as userName0_, user0_.password as password0_ from user user0_ where user0_.id>5 
  70.      *  
  71.      * [User [userId=11, userName=zhangsan, password=zs]] 
  72.      *  
  73.      */  
  74.     public static void testHQLSelectUser(){  
  75.         Session session = sessionFactory.openSession();  
  76.         List<User> userList = session.createQuery("from User user where user.userId > 5")  
  77.                 .list();  
  78.         System.out.println(userList);  
  79.         session.close();  
  80.     }  
  81.     /** 
  82.      * 6. Criteria 方式测试查询附加条件id>? 
  83.      * Hibernate: select this_.id as id0_0_, this_.userName as userName0_0_, this_.password as password0_0_ from user this_ where this_.id>? 
  84.      *  
  85.      * [User [userId=11, userName=zhangsan, password=zs]] 
  86.      *  
  87.      */  
  88.     public static void testCriteriaSelectUser(){  
  89.         Session session = sessionFactory.openSession();  
  90.         List<User> userList = session.createCriteria(User.class)//  
  91.                 .add(Restrictions.gt("userId", 5L))//  
  92.                 .list();  
  93.         System.out.println(userList);  
  94.         session.close();  
  95.     }  
  96.       
  97.     /** 
  98.      * 5. SQL 方式测试查询like附加条件 
  99.      * Hibernate: select * from user where userName like 'zhan%' 
  100.      *  
  101.      * [User [userId=11, userName=zhangsan, password=zs]] 
  102.      *  
  103.      */  
  104.     public static void testSQLSelectPartUser(){  
  105.         Session session = sessionFactory.openSession();  
  106.         List<User> userList = session.createSQLQuery("select * from user where userName like 'zhan%'")  
  107.                 .addEntity(User.class)  
  108.                 .list();  
  109.         System.out.println(userList);  
  110.         session.close();  
  111.     }  
  112.     /** 
  113.      * 5. HQL 方式测试查询like附加条件 
  114.      * Hibernate: select user0_.id as id0_, user0_.userName as userName0_, user0_.password as password0_ from user user0_ where user0_.userName like 'zhan%' 
  115.      *  
  116.      * [User [userId=11, userName=zhangsan, password=zs]] 
  117.      *  
  118.      */  
  119.     public static void testHQLSelectPartUser(){  
  120.         Session session = sessionFactory.openSession();  
  121.         List<User> userList = session.createQuery("from User user where user.userName like 'zhan%'")  
  122.                 .list();  
  123.         System.out.println(userList);  
  124.         session.close();  
  125.     }  
  126.       
  127.     /** 
  128.      * 5. Criteria 方式测试查询like附加条件 
  129.      * Hibernate: select this_.id as id0_0_, this_.userName as userName0_0_, this_.password as password0_0_ from user this_ where this_.userName like ? 
  130.      *  
  131.      * [User [userId=11, userName=zhangsan, password=zs]] 
  132.      *  
  133.      */  
  134.     public static void testCriteriaSelectPartUser(){  
  135.         Session session = sessionFactory.openSession();  
  136.         List<User> userList = session.createCriteria(User.class)  
  137.                 .add(Restrictions.like("userName""zhan%"))  
  138.                 .list();  
  139.         System.out.println(userList);  
  140.         session.close();  
  141.     }  
  142.       
  143.     /** 
  144.      * 4. SQL 方式测试查询所有的user数据 
  145.      * Hibernate: select * from user 
  146.      *  
  147.      * [User [userId=1, userName=wy, password=1234],  
  148.      * User [userId=2, userName=yy, password=123],  
  149.      * User [userId=3, userName=sd, password=12],  
  150.      * User [userId=4, userName=test, password=sffs],  
  151.      * User [userId=11, userName=zhangsan, password=zs]] 
  152.      */  
  153.     public static void testSQLSelectAllUser(){  
  154.         Session session = sessionFactory.openSession();  
  155.         List<User> userList = session.createSQLQuery("select * from user").addEntity(User.class).list();  
  156.         System.out.println(userList);  
  157.         session.close();  
  158.     }  
  159.     /** 
  160.      * 4. HQL 方式测试查询所有的user数据 
  161.      * Hibernate: select user0_.id as id0_, user0_.userName as userName0_, user0_.password as password0_ from user user0_ 
  162.      *  
  163.      * [User [userId=1, userName=wy, password=1234],  
  164.      * User [userId=2, userName=yy, password=123],  
  165.      * User [userId=3, userName=sd, password=12],  
  166.      * User [userId=4, userName=test, password=sffs],  
  167.      * User [userId=11, userName=zhangsan, password=zs]] 
  168.      */  
  169.     public static void testHQLSelectAllUser(){  
  170.         Session session = sessionFactory.openSession();  
  171.         List<User> userList = session.createQuery("from User").list();  
  172.         System.out.println(userList);  
  173.         session.close();  
  174.     }  
  175.     /** 
  176.      * 4. Criteria 方式测试查询所有的user数据 
  177.      * Hibernate: select this_.id as id0_0_, this_.userName as userName0_0_, this_.password as password0_0_ from user this_ 
  178.      *  
  179.      * [User [userId=1, userName=wy, password=1234],  
  180.      * User [userId=2, userName=yy, password=123],  
  181.      * User [userId=3, userName=sd, password=12],  
  182.      * User [userId=4, userName=test, password=sffs],  
  183.      * User [userId=11, userName=zhangsan, password=zs]] 
  184.      */  
  185.     public static void testCriteriaSelectAllUser(){  
  186.         Session session = sessionFactory.openSession();  
  187.         List<User> userList = session.createCriteria(User.class).list();  
  188.         System.out.println(userList);  
  189.         session.close();  
  190.     }  
  191.       
  192.     /** 
  193.      * 3. 删除用户 
  194.      * Hibernate: delete from user where id=? 
  195.      */  
  196.     public static void testDeleteUser(){  
  197.         User user = new User();  
  198.         user.setUserId(5L);  
  199.         user.setUserName("zhanan");  
  200.         user.setPassword("zb");  
  201.         Session session = sessionFactory.openSession();  
  202.         session.beginTransaction(); // 开启事务  
  203.         session.delete(user);  
  204.         session.getTransaction().commit();// 提交事务  
  205.         session.close();  
  206.     }  
  207.       
  208.     /** 
  209.      * 2. 更新用户 
  210.      * Hibernate: update user set userName=?, password=? where id=? 
  211.      */  
  212.     public static void testUpdateUser(){  
  213.         User user = new User();  
  214.         user.setUserId(5L);  
  215.         user.setUserName("zhanan");  
  216.         user.setPassword("zb");  
  217.         Session session = sessionFactory.openSession();  
  218.         session.beginTransaction(); // 开启事务  
  219.         session.update(user);  
  220.         session.getTransaction().commit();// 提交事务  
  221.         session.close();  
  222.     }  
  223.       
  224.     /** 
  225.      * 1. 添加用户 
  226.      * Hibernate: insert into user (userName, password) values (?, ?) 
  227.      */  
  228.     public static void testInsertUser(){  
  229.         User user = new User();  
  230.         user.setUserId(5L);  
  231.         user.setUserName("zhangsan");  
  232.         user.setPassword("zs");  
  233.         Session session = sessionFactory.openSession();  
  234.         session.beginTransaction(); // 开启事务  
  235.         session.save(user);  
  236.         session.getTransaction().commit();// 提交事务  
  237.         session.close();  
  238.     }  
  239.       
  240.   
  241. }  
0 0