测试代码:

  1. package com.hb3.pack_01;

  2. import org.hibernate.Session;
  3. import org.hibernate.SessionFactory;
  4. import org.hibernate.Transaction;
  5. import org.hibernate.cfg.Configuration;

  6. import com.hb3.pack_01.model.User;

  7. public class BusinessService {

  8.     public static void main(String[] args) {
  9.         
  10.         Configuration config = new Configuration().configure();
  11.         SessionFactory sessionFactory = config.buildSessionFactory();      
  12.         Session session = sessionFactory.openSession();
  13.         
  14.         //insert
  15.         User user = new User();
  16.         user.setName("chenyan");
  17.         //user.setAge(new Integer(23));
  18.         Transaction tx = session.beginTransaction();
  19.         session.save(user);
  20.         tx.commit();
  21.         
  22.         //get
  23.         user = (User) session.get(User.class, user.getId());
  24.         System.out.println(user.getAge());
  25.         
  26.         //update
  27.         user.setAge(new Integer(24));
  28.         tx= session.beginTransaction(); 
  29.         session.update(user);
  30.         tx.commit();

  31.         //load
  32.         user = (User) session.load(User.class, user.getId());
  33.         System.out.println(user.getAge());
  34.         
  35.         //delete
  36.         tx = session.beginTransaction();
            session.delete(user);
            tx.commit();
  37.         
  38.         session.close();
  39.         sessionFactory.close();
  40.     }
  41. }

执行结果:

11:50:50,750  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
11:50:51,156  WARN EhCacheProvider:93 - Could not find configuration [org.hibernate.cache.UpdateTimestampsCache]; using defaults.
11:50:51,171  WARN EhCacheProvider:93 - Could not find configuration [org.hibernate.cache.StandardQueryCache]; using defaults.
Hibernate: insert into user (name, age) values (?, ?)
null
Hibernate: update user set name=?, age=? where id=?
24

修改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">
  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. </hibernate-mapping>

运行结果如下:

12:46:32,062  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
12:46:32,468  WARN EhCacheProvider:93 - Could not find configuration [org.hibernate.cache.UpdateTimestampsCache]; using defaults.
12:46:32,500  WARN EhCacheProvider:93 - Could not find configuration [org.hibernate.cache.StandardQueryCache]; using defaults.
Hibernate: insert into user (name) values (?)
null
Hibernate: update user set age=? where id=?
24
Hibernate: delete from user where id=?

可见:

dynamic-insert和dynamic-update设成true后,分别表示生成的SQL中只插入非空字段以及只修改改变过的字段。

另外,hibernate还提供了saveOrUpdate()方法,因为这个方法很容易出错,故在后续章节着重讲述。

关于查询:

  1. package com.hb3.pack_01;

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

  4. import org.hibernate.Criteria;
  5. import org.hibernate.Query;
  6. import org.hibernate.Session;
  7. import org.hibernate.SessionFactory;
  8. import org.hibernate.cfg.Configuration;
  9. import org.hibernate.criterion.Restrictions;

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

  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.         Criteria criteria = session.createCriteria(User.class);
  19.         List<?> users = criteria.list();
  20.         Iterator<?> iterator = users.iterator();
  21.         System.out.println("id "t name/age");

  22.         while (iterator.hasNext()) {
  23.             User user = (User) iterator.next();
  24.             System.out.println(user.getId() + " "t " + user.getName() + "/" + user.getAge());
  25.         }
  26.         
  27.         //criteria.add(Expression.eq("name", "shenbin"));
  28.         criteria.add(Restrictions.eq("name", "shenbin"));
  29.         users = criteria.list();
  30.         iterator = users.iterator();
  31.         System.out.println("id "t name/age");

  32.         while (iterator.hasNext()) {
  33.             User user = (User) iterator.next();
  34.             System.out.println(user.getId() + " "t " + user.getName() + "/" + user.getAge());
  35.         }
  36.         
  37.         System.out.println("====================================================");
  38.         
  39.         Query query = session.createQuery("from User");
  40.         users = query.list();
  41.         iterator = users.iterator();
  42.         System.out.println("id "t name/age");

  43.         while (iterator.hasNext()) {
  44.             User user = (User) iterator.next();
  45.             System.out.println(user.getId() + " "t " + user.getName() + "/" + user.getAge());
  46.         }
  47.         
  48.         query = session.createQuery("from User user where user.name like ?");
  49.         query.setParameter(0, "shenbin");
  50.         users = query.list();
  51.         iterator = users.iterator();
  52.         System.out.println("id "t name/age");

  53.         while (iterator.hasNext()) {
  54.             User user = (User) iterator.next();
  55.             System.out.println(user.getId() + " "t " + user.getName() + "/" + user.getAge());
  56.         }

  57.         session.close();
  58.         sessionFactory.close();
  59.     }
  60. }

执行结果:

13:05:43,031  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
13:05:43,453  WARN EhCacheProvider:93 - Could not find configuration [org.hibernate.cache.UpdateTimestampsCache]; using defaults.
13:05:43,484  WARN EhCacheProvider:93 - Could not find configuration [org.hibernate.cache.StandardQueryCache]; using defaults.
Hibernate: select this_.id as id0_0_, this_.name as name0_0_, this_.age as age0_0_ from user this_
id   name/age
1   shenbin/29
2   chenyan/24
3   chenyan/24
4   chenyan/24
Hibernate: select this_.id as id0_0_, this_.name as name0_0_, this_.age as age0_0_ from user this_ where this_.name=?
id   name/age
1   shenbin/29
================================================
Hibernate: select user0_.id as id0_, user0_.name as name0_, user0_.age as age0_ from user user0_
id   name/age
1   shenbin/29
2   chenyan/24
3   chenyan/24
4   chenyan/24
Hibernate: select user0_.id as id0_, user0_.name as name0_, user0_.age as age0_ from user user0_ where user0_.name like ?
id   name/age
1   shenbin/29

以上分别演示了使用Criteria对SQL的分装以及透过HQL来进行查询。

注意:

代码中如下部分

//criteria.add(Expression.eq("name", "shenbin"));
criteria.add(Restrictions.eq("name", "shenbin"));

在hibernate3.3以后的版本,可能Expression类会被废除,为了保证代码的向后兼容,请使用Restrictions替代。



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