hibernate3学习笔记(五) saveOrUpdate办法[Java编程]
本文“hibernate3学习笔记(五) saveOrUpdate办法[Java编程]”是由七道奇为您精心收集,来源于网络转载,文章版权归文章作者所有,本站不对其观点以及内容做任何评价,请读者自行判断,以下是其具体内容:
还是参考前面的例子: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();
}
}
以上是“hibernate3学习笔记(五) saveOrUpdate办法[Java编程]”的内容,如果你对以上该文章内容感兴趣,你可以看看七道奇为您推荐以下文章:
本文地址: | 与您的QQ/BBS好友分享! |