hibernate查询方式:HQL、SQL、Criteria方法、命名、动态分离查询、例子查询

 
转载于:http://blog.csdn.net/vbubble/article/details/7048272
  1. mysql> select * from product;  
  2. +----+--------+----------+   
  3. | id | name   | qq       |  
  4. +----+--------+----------+   
  5. |  1 | apple  | 20121212 |  
  6. |  2 | orange | 20111111 |  
  7. |  3 | banana | 20122222 |  
  8. |  4 | apple  | 20122222 |  
  9. |  5 | apple  | 20122222 |  
  10. |  6 | apple  | 201222qq |  
  11. +----+--------+----------+   
  12. rows in set (0.00 sec)  
  13.   
  14. mysql>  


【1、HQL查询】:


hibernate管理类!

  1. package com.bubble.util;  
  2.   
  3. import org.hibernate.HibernateException;  
  4. import org.hibernate.Session;  
  5. import org.hibernate.SessionFactory;  
  6. import org.hibernate.cfg.AnnotationConfiguration;  
  7.   
  8. /** 
  9.  * @author bubble  
  10.  * 
  11.  */  
  12. public class HibernateUtil {  
  13.       
  14.     // single    
  15.     private static final SessionFactory sessionFactory;  
  16.       
  17.     static{  
  18.         try{  
  19.             //class AnnotationConfiguration:读取关于Annotation的配置   
  20.         sessionFactory=new AnnotationConfiguration().configure().buildSessionFactory();  
  21.         }catch (Throwable e) {  
  22.             // TODO: handle exception   
  23.             throw new ExceptionInInitializerError(e);  
  24.         }  
  25.     }  
  26.       
  27.     // static method to get session   
  28.     public static Session getSession() throws HibernateException{  
  29.           
  30.         return sessionFactory.openSession();  
  31.           
  32.     }  
  33.       
  34.     // close session factory   
  35.     public static void closeSessionFactory(){  
  36.           
  37.         sessionFactory.close();  
  38.           
  39.     }  
  40.   
  41. }  



测试HQL查询方式的代码!

  1. package com.bubble.test;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.hibernate.Query;  
  6. import org.hibernate.Session;  
  7.   
  8. import com.bubble.entity.Product;  
  9. import com.bubble.util.HibernateUtil;  
  10.   
  11. public class HqlTest {  
  12.    
  13.     /** 
  14.      * @author bubble 11 / 12 / 07 
  15.      * HQL具有跨数据库的优点。 
  16.      * 适用情况:常用方法,比较传统,类似jdbc。 
  17.      * 缺点:新的查询语言,适用面有限,仅适用于Hibernate框架。 
  18.      */  
  19.     public static void main(String[] args) {  
  20.         // TODO Auto-generated method stub   
  21.         Session session=HibernateUtil.getSession();// get session   
  22.           
  23.         //String hql="from Product as product where product.name= ? ";// hql    
  24.         // same to the ? method    
  25.         String hql="from Product as product where product.name=:name";// 命名参数    
  26.           
  27.         Query  query = session.createQuery(hql); // create query object   
  28.           
  29.     // query.setString(0, "apple");// set the value of first ?   
  30.         query.setString("name","apple");  
  31.           
  32.         List<Product> list=query.list();// get product if product's name=apple   
  33.           
  34.         for (Product product : list) {  
  35.             // print product's info   
  36.             System.out.println("name is:"+product.getName()+"\tQQ shenma is:"+product.getQq());  
  37.               
  38.         }  
  39.         // close   
  40.         session.close();  
  41.           
  42.         HibernateUtil.closeSessionFactory();  
  43.   
  44.     }  
  45.   
  46. }  

查询结果!

  1. 2011-12-7 1:46:54 org.hibernate.cfg.annotations.Version <clinit>  
  2. 信息: Hibernate Annotations 3.3.0.GA  
  3. 2011-12-7 1:46:54 org.hibernate.cfg.Environment <clinit>  
  4. 信息: Hibernate 3.2.5  
  5. 2011-12-7 1:46:54 org.hibernate.cfg.Environment <clinit>  
  6. 信息: hibernate.properties not found  
  7. 2011-12-7 1:46:54 org.hibernate.cfg.Environment buildBytecodeProvider  
  8. 信息: Bytecode provider name : cglib  
  9. 2011-12-7 1:46:54 org.hibernate.cfg.Environment <clinit>  
  10. 信息: using JDK 1.4 java.sql.Timestamp handling  
  11. 2011-12-7 1:46:54 org.hibernate.cfg.Configuration configure  
  12. 信息: configuring from resource: /hibernate.cfg.xml  
  13. 2011-12-7 1:46:54 org.hibernate.cfg.Configuration getConfigurationInputStream  
  14. 信息: Configuration resource: /hibernate.cfg.xml  
  15. 2011-12-7 1:46:54 org.hibernate.cfg.Configuration doConfigure  
  16. 信息: Configured SessionFactory: null  
  17. 2011-12-7 1:46:54 org.hibernate.cfg.AnnotationBinder bindClass  
  18. 信息: Binding entity from annotated class: com.bubble.entity.Product  
  19. 2011-12-7 1:46:54 org.hibernate.cfg.annotations.EntityBinder bindTable  
  20. 信息: Bind entity com.bubble.entity.Product on table Product  
  21. 2011-12-7 1:46:54 org.hibernate.validator.Version <clinit>  
  22. 信息: Hibernate Validator 3.0.0.GA  
  23. 2011-12-7 1:46:55 org.hibernate.connection.DriverManagerConnectionProvider configure  
  24. 信息: Using Hibernate built-in connection pool (not for production use!)  
  25. 2011-12-7 1:46:55 org.hibernate.connection.DriverManagerConnectionProvider configure  
  26. 信息: Hibernate connection pool size: 20  
  27. 2011-12-7 1:46:55 org.hibernate.connection.DriverManagerConnectionProvider configure  
  28. 信息: autocommit mode: false  
  29. 2011-12-7 1:46:55 org.hibernate.connection.DriverManagerConnectionProvider configure  
  30. 信息: using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost:3306/hiber001  
  31. 2011-12-7 1:46:55 org.hibernate.connection.DriverManagerConnectionProvider configure  
  32. 信息: connection properties: {user=root, password=****}  
  33. 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings  
  34. 信息: RDBMS: MySQL, version: 5.1.45-community-log  
  35. 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings  
  36. 信息: JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-5.1.13 ( Revision: ${bzr.revision-id} )  
  37. 2011-12-7 1:46:55 org.hibernate.dialect.Dialect <init>  
  38. 信息: Using dialect: org.hibernate.dialect.MySQLDialect  
  39. 2011-12-7 1:46:55 org.hibernate.transaction.TransactionFactoryFactory buildTransactionFactory  
  40. 信息: Using default transaction strategy (direct JDBC transactions)  
  41. 2011-12-7 1:46:55 org.hibernate.transaction.TransactionManagerLookupFactory getTransactionManagerLookup  
  42. 信息: No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)  
  43. 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings  
  44. 信息: Automatic flush during beforeCompletion(): disabled  
  45. 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings  
  46. 信息: Automatic session close at end of transaction: disabled  
  47. 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings  
  48. 信息: JDBC batch size: 15  
  49. 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings  
  50. 信息: JDBC batch updates for versioned data: disabled  
  51. 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings  
  52. 信息: Scrollable result sets: enabled  
  53. 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings  
  54. 信息: JDBC3 getGeneratedKeys(): enabled  
  55. 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings  
  56. 信息: Connection release mode: auto  
  57. 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings  
  58. 信息: Maximum outer join fetch depth: 2  
  59. 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings  
  60. 信息: Default batch fetch size: 1  
  61. 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings  
  62. 信息: Generate SQL with comments: disabled  
  63. 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings  
  64. 信息: Order SQL updates by primary key: disabled  
  65. 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings  
  66. 信息: Order SQL inserts for batching: disabled  
  67. 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory createQueryTranslatorFactory  
  68. 信息: Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory  
  69. 2011-12-7 1:46:55 org.hibernate.hql.ast.ASTQueryTranslatorFactory <init>  
  70. 信息: Using ASTQueryTranslatorFactory  
  71. 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings  
  72. 信息: Query language substitutions: {}  
  73. 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings  
  74. 信息: JPA-QL strict compliance: disabled  
  75. 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings  
  76. 信息: Second-level cache: enabled  
  77. 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings  
  78. 信息: Query cache: disabled  
  79. 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory createCacheProvider  
  80. 信息: Cache provider: org.hibernate.cache.NoCacheProvider  
  81. 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings  
  82. 信息: Optimize cache for minimal puts: disabled  
  83. 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings  
  84. 信息: Structured second-level cache entries: disabled  
  85. 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings  
  86. 信息: Echoing all SQL to stdout  
  87. 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings  
  88. 信息: Statistics: disabled  
  89. 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings  
  90. 信息: Deleted entity synthetic identifier rollback: disabled  
  91. 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings  
  92. 信息: Default entity-mode: pojo  
  93. 2011-12-7 1:46:55 org.hibernate.cfg.SettingsFactory buildSettings  
  94. 信息: Named query checking : enabled  
  95. 2011-12-7 1:46:55 org.hibernate.impl.SessionFactoryImpl <init>  
  96. 信息: building session factory  
  97. 2011-12-7 1:46:55 org.hibernate.impl.SessionFactoryObjectFactory addInstance  
  98. 信息: Not binding factory to JNDI, no JNDI name configured  
  99. <span style="color:#ff0000;"><strong>Hibernate: select product0_.id as id0_, product0_.name as name0_, product0_.qq as qq0_ from Product product0_ where product0_.name=?</strong></span>  
  100. <strong><span style="color:#009900;">name is:apple  QQ shenma is:20121212  
  101. name is:apple   QQ shenma is:20122222  
  102. name is:apple   QQ shenma is:20122222  
  103. name is:apple   QQ shenma is:201222qq</span></strong>  
  104. 2011-12-7 1:46:55 org.hibernate.impl.SessionFactoryImpl close  
  105. 信息: closing  
  106. 2011-12-7 1:46:55 org.hibernate.connection.DriverManagerConnectionProvider close  
  107. 信息: cleaning up connection pool: jdbc:mysql://localhost:3306/hiber001  

-------------------------------------------------------------------------------------------------------------------------------

【2、对象化查询Criteria方法】:

Criteria查询代码! 

  1. package com.bubble.test;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.hibernate.Criteria;  
  6. import org.hibernate.Query;  
  7. import org.hibernate.Session;  
  8. import org.hibernate.criterion.Restrictions;  
  9.   
  10. import com.bubble.entity.Product;  
  11. import com.bubble.util.HibernateUtil;  
  12.   
  13. public class CriteriaTest {  
  14.    
  15.     /** 
  16.      * @author bubble 11 / 12 / 07 
  17.      * 适用情况:面向对象操作,革新了以前的数据库操作方式,易读。 
  18.      * 缺点:适用面较HQL有限。 
  19.      *  
  20.      */  
  21.     public static void main(String[] args) {  
  22.         // TODO Auto-generated method stub   
  23.         Session session=HibernateUtil.getSession();// get session   
  24.           
  25.         Criteria criteria = session.createCriteria(Product.class);  
  26.           
  27.         criteria.add(Restrictions.eq("name""apple"));// Restrictions:get product's name which eq apple ,like the where Restrictions in hql   
  28.         //eq是等于,gt是大于,lt是小于,or是或   
  29.         criteria.add(Restrictions.gt("id"3)); // when id > 3   
  30.        
  31.         List<Product> list=criteria.list();// get product if product's name=apple and id>3   
  32.           
  33.         for (Product product : list) {  
  34.             // print product's info   
  35.             System.out.println("name is:"+product.getName()+"\tQQ shenma is:"+product.getQq());  
  36.               
  37.         }  
  38.         // close   
  39.         session.close();  
  40.           
  41.         HibernateUtil.closeSessionFactory();  
  42.   
  43.     }  
  44.   
  45. }  

查询结果!

  1. Hibernate: select this_.id as id0_0_, this_.name as name0_0_, this_.qq as qq0_0_ from Product this_ where this_.name=? and this_.id>?  
  2. name is:apple   QQ shenma is:20122222  
  3. name is:apple   QQ shenma is:20122222  
  4. name is:apple   QQ shenma is:201222qq  


-------------------------------------------------------------------------------------------
【3、动态分离查询DetachedCriteria

detachedcriteria查询方式代码!

  1. package com.bubble.test;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.hibernate.Criteria;  
  6. import org.hibernate.Session;  
  7. import org.hibernate.criterion.DetachedCriteria;  
  8. import org.hibernate.criterion.Restrictions;  
  9.   
  10. import com.bubble.entity.Product;  
  11. import com.bubble.util.HibernateUtil;  
  12.   
  13. /** 
  14.  * @author bubble 11 / 12 / 07  
  15.  * 适用情况:面向对象操作,分离业务与底层,不需要字段属性摄入到Dao实现层。 
  16.  * 缺点:适用面较HQL有限。 
  17.  */  
  18. public class DetachedCriteriaTest {  
  19.   
  20.     // get result from database ,return list   
  21.     public static List dc(DetachedCriteria dc) {  
  22.         Session session = HibernateUtil.getSession();  
  23.         Criteria c = dc.getExecutableCriteria(session);  
  24.         List<Criteria> list = c.list();  
  25.         session.close();  
  26.         return list;  
  27.     }  
  28.   
  29.     // main method   
  30.     public static void main(String[] args) {  
  31.   
  32.         DetachedCriteria dc = DetachedCriteria.forClass(Product.class);  
  33.         int id = 1;  
  34.         String name = "apple";  
  35.         if (id != 0)  
  36.             dc.add(Restrictions.gt("id", id));  
  37.         if (name != null)  
  38.             dc.add(Restrictions.eq("name", name));  
  39.         List<Product> list = dc(dc);  
  40.         System.out.println("离线查询返回结果:--------------------");  
  41.         for (Product product : list) {  
  42.             // print product's info   
  43.             System.out.println("name is:" + product.getName()  
  44.                     + "\tQQ shenma is:" + product.getQq());  
  45.   
  46.         }  
  47.   
  48.     }  
  49.   
  50. }  

结果!

  1. Hibernate: select this_.id as id0_0_, this_.name as name0_0_, this_.qq as qq0_0_ from Product this_ where this_.id>? and this_.name=?  
  2. 离线查询返回结果:--------------------  
  3. name is:apple   QQ shenma is:20122222  
  4. name is:apple   QQ shenma is:20122222  
  5. name is:apple   QQ shenma is:201222qq  


---------------------------------------------------------- ---------------------------------------------------------------------------------------------
【4、例子查询

例子查询代码!

  1. package com.bubble.test;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.hibernate.Session;  
  6. import org.hibernate.criterion.Example;  
  7.   
  8. import com.bubble.entity.Product;  
  9. import com.bubble.util.HibernateUtil;  
  10.   
  11. /** 
  12.  * @author bubble 11 / 12 / 07 
  13.  * 适用情况:面向对象操作。    
  14.  * 缺点:适用面较HQL有限,不推荐。 
  15.  */  
  16. public class ExampleTest {  
  17.    
  18.   
  19.     public static void main(String[] args) {  
  20.         // TODO Auto-generated method stub   
  21.         Session session=HibernateUtil.getSession();// get session   
  22.           
  23.         List<Product> products = session.createCriteria(Product.class).add(Example.create(new Product())).list();  
  24.           
  25.         for (Product product : products) {  
  26.             // print product's info   
  27.             System.out.println("name is:" + product.getName()  
  28.                     + "\tQQ shenma is:" + product.getQq());  
  29.   
  30.         }  
  31.         // close   
  32.         session.close();  
  33.           
  34.         HibernateUtil.closeSessionFactory();  
  35.   
  36.     }  
  37.   
  38. }  

查询结果!

  1. Hibernate: select this_.id as id0_0_, this_.name as name0_0_, this_.qq as qq0_0_ from Product this_ where (1=1)  
  2. name is:apple   QQ shenma is:20121212  
  3. name is:orange  QQ shenma is:20111111  
  4. name is:banana  QQ shenma is:20122222  
  5. name is:apple   QQ shenma is:20122222  
  6. name is:apple   QQ shenma is:20122222  
  7. name is:apple   QQ shenma is:201222qq  

【5、sql查询

sql查询代码!

  1. package com.bubble.test;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.hibernate.Query;  
  6. import org.hibernate.Session;  
  7.   
  8. import com.bubble.entity.Product;  
  9. import com.bubble.util.HibernateUtil;  
  10.   
  11.   
  12. /** 
  13.  * @author bubble 11 / 12 / 07 
  14.  * 适用情况:不熟悉HQL的朋友,又不打算转数据库平台的朋友,万能方法  
  15.  * 缺点:破坏跨平台,不易维护,不面向对象。 
  16.  */  
  17. public class SqlTest {  
  18.    
  19.     public static void main(String[] args) {  
  20.         // TODO Auto-generated method stub   
  21.         Session session=HibernateUtil.getSession();// get session   
  22.           
  23.         Query query = session.createSQLQuery("select * from product").addEntity(Product.class);// create sql statement   
  24.           
  25.         List<Product> list=query.list();// get all products   
  26.           
  27.         for (Product product : list) {  
  28.             // print product's info   
  29.             System.out.println("name is:"+product.getName()+"\tid is:"+product.getId());  
  30.               
  31.         }  
  32.         // close   
  33.         session.close();  
  34.           
  35.         HibernateUtil.closeSessionFactory();  
  36.   
  37.     }  
  38.   
  39. }  

结果!

  1. <span style="font-size:24px;color:#ff0000;"><strong>Hibernate: select * from product</strong></span><span style="font-size:13px; ">  
  2. name is:apple   id is:1  
  3. name is:orange  id is:2  
  4. name is:banana  id is:3  
  5. name is:apple   id is:4  
  6. name is:apple   id is:5  
  7. name is:apple   id is:6</span>  

-----------------------------------------------------------------------------------------------------------

【6、命名查询】

之前是使用hibernate注解来进行映射的,现在注释掉注解映射

hibernate.cfg.xml

  1. <?xml version='1.0' encoding='UTF-8'?>  
  2. <!DOCTYPE hibernate-configuration PUBLIC  
  3.           "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
  4.           "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
  5. <!-- Generated by MyEclipse Hibernate Tools.                   -->  
  6. <hibernate-configuration>  
  7. <session-factory>  
  8.     <property name="dialect">  
  9.         org.hibernate.dialect.MySQLDialect  
  10.     </property>  
  11.     <property name="connection.url">  
  12.         jdbc:mysql://localhost:3306/hiber001  
  13.     </property>  
  14.     <property name="connection.username">root</property>  
  15.     <property name="connection.password">123456</property>  
  16.     <property name="connection.driver_class">  
  17.         com.mysql.jdbc.Driver  
  18.     </property>  
  19.     <property name="myeclipse.connection.profile">mysql5</property>  
  20.     <property name="show_sql">true</property>  
  21.     <!-- annotation part -->  
  22.     <!-- <mapping class="com.bubble.entity.Product" /> -->  
  23.     <mapping resource="com/bubble/entity/Product.hbm.xml" />   
  24.   
  25. </session-factory>  
  26.   
  27. </hibernate-configuration>  

命名查询代码!

  1. package com.bubble.test;  
  2.   
  3.   
  4. /** 
  5.  * @author bubble 11 / 12 / 07 
  6.  * 适用情况:万能方法,有点像ibatis轻量级框架的操作,方便维护。 
  7.  * 缺点:不面向对象。基于hql和sql,有一定缺陷 
  8.  */  
  9. import java.util.List;  
  10.   
  11. import org.hibernate.Query;  
  12. import org.hibernate.Session;  
  13.   
  14. import com.bubble.entity.Product;  
  15. import com.bubble.util.HibernateUtil;  
  16.    
  17. public class NamedTest {  
  18.   
  19.     public static void main(String[] args) {  
  20.         // TODO Auto-generated method stub   
  21.         Session session=HibernateUtil.getSession();// get session   
  22.           
  23.         Query query = session.getNamedQuery("getProductByName");  
  24.           
  25.         query.setString("name","apple");  
  26.           
  27.         List<Product> list=query.list();// get all products named apple   
  28.           
  29.         for (Product product : list) {  
  30.             // print product's info   
  31.             System.out.println("name is:"+product.getName()+"\tid is:"+product.getId());  
  32.               
  33.         }  
  34.         // close   
  35.         session.close();  
  36.           
  37.         HibernateUtil.closeSessionFactory();  
  38.   
  39.     }  
  40.   
  41. }<strong>  
  42. </strong>  

查询结果!

  1. Hibernate: select product0_.id as id0_, product0_.name as name0_, product0_.qq as qq0_ from hiber001.product product0_ where product0_.name=?  
  2. name is:apple   id is:1  
  3. name is:apple   id is:4  
  4. name is:apple   id is:5  
  5. name is:apple   id is:6  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值