hibernate3学习笔记(五) saveOrUpdate方法 - 编程入门网
hibernate3学习笔记(五) saveOrUpdate方法时间:2011-02-01还是参考前面的例子: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方法(2)时间:2011-02-01运行结果 |
凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站:http://www.lingzhong.cn 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢! |