還是參考前面的例子:http://blog.csdn.net/kunshan_shenbin/archive/2008/09/02/2864883.aspx
修改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>
</hibernate-mapping>
測試代碼:
package com.hb3.pack_01;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Criteria;
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;
public class BusinessService {
public static void main(String[] args) {
Configuration config = new Configuration().configure();
SessionFactory sessionFactory = config.buildSessionFactory();
Session session = sessionFactory.openSession();
Criteria criteria = session.createCriteria(User.class);
List<?> users = criteria.list();
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());
}
session.close();
System.out.println("========================================");
session = sessionFactory.openSession();
User user = new User();
user.setId(2);
user.setName("chenyan");
user.setAge(new Integer(24));
Transaction tx = session.beginTransaction();
session.saveOrUpdate(user);
tx.commit();
System.out.println("========================================");
user = new User();
user.setName("yangye");
user.setAge(new Integer(23));
tx = session.beginTransaction();
session.saveOrUpdate(user);
tx.commit();
System.out.println("========================================");
Query query = session.createQuery("from User");
users = query.list();
iterator = users.iterator();
System.out.println("id \t name/age");
while (iterator.hasNext()) {
user = (User) iterator.next();
System.out.println(user.getId() + " \t " + user.getName() + "/" + user.getAge());
}
session.close();
sessionFactory.close();
}
}
運行結果:
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