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

测试代码:

  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.Transaction;
  9. import org.hibernate.cfg.Configuration;

  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.         session.close();
  27.         
  28.         System.out.println("========================================");
  29.         
  30.         session = sessionFactory.openSession();
  31.         User user = new User();
  32.         user.setId(2);
  33.         user.setName("chenyan");
  34.         user.setAge(new Integer(24));
  35.         Transaction tx = session.beginTransaction();
  36.         session.saveOrUpdate(user);
  37.         tx.commit();
  38.         
  39.         System.out.println("========================================");
  40.         
  41.         user = new User();
  42.         user.setName("yangye");
  43.         user.setAge(new Integer(23));
  44.         tx = session.beginTransaction();
  45.         session.saveOrUpdate(user);
  46.         tx.commit();
  47.         
  48.         System.out.println("========================================");
  49.         
  50.         Query query = session.createQuery("from User");
  51.         users = query.list();
  52.         iterator = users.iterator();
  53.         System.out.println("id "t name/age");

  54.         while (iterator.hasNext()) {
  55.             user = (User) iterator.next();
  56.             System.out.println(user.getId() + " "t " + user.getName() + "/" + user.getAge());
  57.         }
  58.         
  59.         session.close();
  60.         sessionFactory.close();
  61.     }
  62. }

运行结果:

13:45:00,140  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:45:00,703  WARN EhCacheProvider:93 - Could not find configuration [org.hibernate.cache.UpdateTimestampsCache]; using defaults.
13:45:00,734  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/28
2   chenyan/25
========================================
Hibernate: update user set name=?, age=? where id=?
========================================
Hibernate: insert into user (name, age) values (?, ?)
========================================
Hibernate: select user0_.id as id0_, user0_.name as name0_, user0_.age as age0_ from user user0_
id   name/age
1   shenbin/28
2   chenyan/24
3   yangye/23

提示:

unsaved-value可以设定的值包括:

any:总是存储

none:总是更新

null:id为null时存储(默认)

valid:id为null或是指定值时存储

值得一提的是:

正如上面的代码所示,使用查询语句查出对象后,不能使用同一个session直接对对象进行修改操作。否则会抛出异常:

Exception in thread "main" org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [com.hb3.pack_01.model.User#2]

......

当然这并不是saveOrUpdate方法独有的。save和update等方法使用不当也会出现如上异常。

解决方法可新建session, 或参阅:

http://www.blogjava.net/Unmi/archive/2007/08/10/135771.html

http://blog.csdn.net/tmpfree/archive/2006/03/13/623516.aspx

http://www.javaeye.com/topic/11581



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