示例代码如下:
- package com.hb3.pack_01;
- import java.util.Iterator;
- import java.util.List;
- import org.hibernate.Query;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.Transaction;
- import org.hibernate.cfg.Configuration;
- import com.hb3.pack_01.model.User;
- import com.hb3.pack_01.model.UserBak;
- public class BusinessService {
- public static void main(String[] args) {
-
- Configuration config = new Configuration().configure();
- SessionFactory sessionFactory = config.buildSessionFactory();
- Session session = sessionFactory.openSession();
-
- Query query = session.createQuery("from com.hb3.pack_01.model.User user order by user.age desc, user.name");
- printUserInfo(query.list());
-
- query = session.createQuery("select new com.hb3.pack_01.model.UserBak(user.name, user.age) from User as user");
- Iterator<?> iterator = query.list().iterator();
- System.out.println("class_name \t\t name/age");
- while (iterator.hasNext()) {
- UserBak userbak = (UserBak) iterator.next();
- System.out.println(userbak.getClz() + " \t " + userbak.getName() + "/" + userbak.getAge());
- }
-
- query = session.createQuery("select upper(user.name) from User as user where (user.age/2 >= ?) and (user.age is not null)");
- query.setInteger(0, 13);
- List<?> names = query.list();
- iterator = names.iterator();
- while(iterator.hasNext()) {
- System.out.println(iterator.next());
- }
-
- query = session.createQuery("select user.name, user.age from User as user where user.age > :minAge");
- query.setInteger("minAge", 25);
- names = query.list();
- iterator = names.iterator();
- while(iterator.hasNext()) {
- Object[] obj = (Object[]) iterator.next();
- System.out.println(obj[0] + "\t" + obj[1]);
- }
-
- query = session.getNamedQuery("com.hb3.pack_01.model.User.QueryUser");
- query.setInteger("minAge", 25);
- printUserInfo(query.list());
-
- Transaction tx= session.beginTransaction();
- query = session.createQuery("update User set age=24 where name='chenyan'");
- query.executeUpdate();
- tx.commit();
- tx= session.beginTransaction();
- query = session.createQuery("delete User where name='yaobin'");
- query.executeUpdate();
- tx.commit();
-
- session.close();
- sessionFactory.close();
- }
-
- public static void printUserInfo(List<?> users){
-
- Iterator<?> iterator = users.iterator();
- System.out.println("id \t name/age");
- while (iterator.hasNext()) {
- User user = (User) iterator.next();
- System.out.println(user.getId() + " \t " + user.getName() + "/" + user.getAge());
- }
- }
- }
修改User.hbm.xml文件;
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- <hibernate-mapping>
- <class name="com.hb3.pack_01.model.User" table="user"
- dynamic-insert="true"
- dynamic-update="true"
- >
- <id name="id" column="id" type="java.lang.Integer" unsaved-value="null">
- <generator class="native" />
- </id>
-
- <property name="name" column="name" type="java.lang.String" />
-
- <property name="age" column="age" type="java.lang.Integer" />
- </class>
-
- <query name="com.hb3.pack_01.model.User.QueryUser">
- <![CDATA[
- from User as user where user.age > :minAge
- ]]>
- </query>
-
- </hibernate-mapping>
新建UserBak类
- package com.hb3.pack_01.model;
- public class UserBak {
- private String clz = "UserBak";
- private String name;
- private Integer age;
-
- public UserBak() {
- }
-
- public UserBak(String name, Integer age) {
- this.name = name;
- this.age = age;
- }
-
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public Integer getAge() {
- return age;
- }
- public void setAge(Integer age) {
- this.age = age;
- }
- public String getClz() {
- return clz;
- }
- public void setClz(String clz) {
- this.clz = clz;
- }
- }
运行结果:
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教程