示例代码如下:

  1. package com.hb3.pack_01;

  2. import java.util.Iterator;
  3. import java.util.List;

  4. import org.hibernate.Query;
  5. import org.hibernate.Session;
  6. import org.hibernate.SessionFactory;
  7. import org.hibernate.Transaction;
  8. import org.hibernate.cfg.Configuration;

  9. import com.hb3.pack_01.model.User;
  10. import com.hb3.pack_01.model.UserBak;

  11. public class BusinessService {

  12.     public static void main(String[] args) {
  13.         
  14.         Configuration config = new Configuration().configure();
  15.         SessionFactory sessionFactory = config.buildSessionFactory();      
  16.         Session session = sessionFactory.openSession();
  17.         
  18.         Query query = session.createQuery("from com.hb3.pack_01.model.User user order by user.age desc, user.name");//[== from User]
  19.         printUserInfo(query.list());
  20.         
  21.         query = session.createQuery("select new com.hb3.pack_01.model.UserBak(user.name, user.age) from User as user");
  22.         Iterator<?> iterator = query.list().iterator();
  23.         System.out.println("class_name \t\t name/age");
  24.         while (iterator.hasNext()) {
  25.             UserBak userbak = (UserBak) iterator.next();
  26.             System.out.println(userbak.getClz() + " \t " + userbak.getName() + "/" + userbak.getAge());
  27.         }
  28.         
  29.         query = session.createQuery("select upper(user.name) from User as user where (user.age/2 >= ?) and (user.age is not null)"); 
  30.         query.setInteger(013);
  31.         List<?> names = query.list();
  32.         iterator =  names.iterator();
  33.         while(iterator.hasNext()) {
  34.             System.out.println(iterator.next());
  35.         }
  36.         
  37.         query = session.createQuery("select user.name, user.age from User as user where user.age > :minAge"); 
  38.         query.setInteger("minAge"25);
  39.         names = query.list();
  40.         iterator =  names.iterator();
  41.         while(iterator.hasNext()) {
  42.             Object[] obj = (Object[]) iterator.next();
  43.             System.out.println(obj[0] + "\t" + obj[1]);
  44.         }
  45.         
  46.         query = session.getNamedQuery("com.hb3.pack_01.model.User.QueryUser"); 
  47.         query.setInteger("minAge"25);
  48.         printUserInfo(query.list());
  49.         
  50.         Transaction tx= session.beginTransaction();
  51.         query = session.createQuery("update User set age=24 where name='chenyan'");
  52.         query.executeUpdate();
  53.         tx.commit();

  54.         tx= session.beginTransaction();
  55.         query = session.createQuery("delete User where name='yaobin'");
  56.         query.executeUpdate();
  57.         tx.commit();
  58.         
  59.         session.close();
  60.         sessionFactory.close();
  61.     }
  62.     
  63.     public static void printUserInfo(List<?> users){
  64.         
  65.         Iterator<?> iterator = users.iterator();
  66.         System.out.println("id \t name/age");
  67.         while (iterator.hasNext()) {
  68.             User user = (User) iterator.next();
  69.             System.out.println(user.getId() + " \t " + user.getName() + "/" + user.getAge());
  70.         }
  71.     }
  72. }

修改User.hbm.xml文件;

  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>
  6.     <class name="com.hb3.pack_01.model.User" table="user" 
  7.         dynamic-insert="true" 
  8.         dynamic-update="true"   
  9.     >
  10.         <id name="id" column="id" type="java.lang.Integer" unsaved-value="null">
  11.             <generator class="native" />
  12.         </id>
  13.         
  14.         <property name="name" column="name" type="java.lang.String" />
  15.         
  16.         <property name="age" column="age" type="java.lang.Integer" />
  17.     </class>
  18.     
  19.     <query name="com.hb3.pack_01.model.User.QueryUser">
  20.         <![CDATA[             
  21.             from User as user where user.age >  :minAge        
  22.         ]]>
  23.     </query>
  24.     
  25. </hibernate-mapping>

新建UserBak类

  1. package com.hb3.pack_01.model;

  2. public class UserBak {

  3.     private String clz = "UserBak";
  4.     private String name;
  5.     private Integer age;
  6.     
  7.     public UserBak() {
  8.     }
  9.     
  10.     public UserBak(String name, Integer age) {
  11.         this.name = name;
  12.         this.age = age;
  13.     }
  14.     
  15.     public String getName() {
  16.         return name;
  17.     }
  18.     public void setName(String name) {
  19.         this.name = name;
  20.     }
  21.     public Integer getAge() {
  22.         return age;
  23.     }
  24.     public void setAge(Integer age) {
  25.         this.age = age;
  26.     }
  27.     public String getClz() {
  28.         return clz;
  29.     }
  30.     public void setClz(String clz) {
  31.         this.clz = clz;
  32.     }
  33. }

运行结果:

16:53:02,015  WARN ConfigurationFactory:127 - No configuration found. Configuring ehcache from ehcache-failsafe.xml  found in the classpath: jar:file:/D:/Java/MyEclipse%206.0/workspace/hb3demo/ehcache-1.2.3.jar!/ehcache-failsafe.xml
16:53:02,437  WARN EhCacheProvider:93 - Could not find configuration [org.hibernate.cache.UpdateTimestampsCache]; using defaults.
16:53:02,468  WARN EhCacheProvider:93 - Could not find configuration [org.hibernate.cache.StandardQueryCache]; using defaults.
Hibernate: select user0_.id as id0_, user0_.name as name0_, user0_.age as age0_ from user user0_ order by user0_.age desc, user0_.name
id   name/age
1   shenbin/28
2   chenyan/26
9   shenyi/23
10   yangye/23
11   chenyong/22
13   chendong/null
12   yaobin/null
Hibernate: select user0_.name as col_0_0_, user0_.age as col_1_0_ from user user0_
class_name    name/age
UserBak   shenbin/28
UserBak   chenyan/26
UserBak   shenyi/23
UserBak   yangye/23
UserBak   chenyong/22
UserBak   yaobin/null
UserBak   chendong/null
Hibernate: select upper(user0_.name) as col_0_0_ from user user0_ where user0_.age/2>=? and (user0_.age is not null)
SHENBIN
CHENYAN
Hibernate: select user0_.name as col_0_0_, user0_.age as col_1_0_ from user user0_ where user0_.age>?
shenbin 28
chenyan 26
Hibernate: select user0_.id as id0_, user0_.name as name0_, user0_.age as age0_ from user user0_ where user0_.age>?
id   name/age
1   shenbin/28
2   chenyan/26
Hibernate: update user set age=24 where name='chenyan'
Hibernate: delete from user where name='yaobin'

 

注意点:

1.在Hibernate3中,可以直接使用HQL指定更新或刪除。

2.使用HQL可以自定义返回的类型。(如:UserBak)

3.使用HQL可以结合各种查询条件,使用where子句限定查询条件,除了 = 运算之外,还有 >、>=、<、<=、!= 或 <>等比较运算:

Query query = session.createQuery("from User user where user.age between 20 and 30");

Query query = session.createQuery("from User user where user.name in('caterpillar', 'momor')");

Query query = session.createQuery("from User user where user.name like 'cater%'");

Query query = session.createQuery("select avg(user.age) from User as user");

Query query = session.createQuery("select count(*) from User as user");

也可以配合GROUP BY子句,假设在数据库表中追加一个Sex字段。

Query query = session.createQuery("select user.sex, avg(user.age) from User user group by user.sex");

运行结果可能是:

+-------------------------------+ 
| sex | avg(age) |
+-------------------------------+
| male | 30 |
+-------------------------------+
| female | 25 |
+-------------------------------+

可以結合having子句,例如只将平均年龄大于20的资料分组显示出来:
Query query = session.createQuery("select user.sex, avg(user.age) from User user group by user.sex having avg(user.age) > 20");

使用HQL是官方推荐的查询方式。



ExtJS教程- Hibernate教程-Struts2 教程-Lucene教程