package com.ru.service; import static org.junit.Assert.*; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.junit.Test; import com.ru.domain.Classes; public class LifeTest { Configuration cf=new Configuration().configure(); SessionFactory sf=cf.buildSessionFactory(); Session session1=null; Session session2=null; Session session3=null; Session session4=null; Classes clazz=null; int id=0; @Test public void save() { //研究session的生命周期 try { //save()方法 session1=sf.openSession(); Transaction tx=session1.beginTransaction(); clazz=new Classes(); clazz.setName("云1"); //clazz对象被放到session缓存中,session缓存中的clazz变量指向classes对象内存。在提交事务之前数据不会被存放到数据库 //clazz和clazz2变成持久态 session1.save(clazz); id=clazz.getId(); tx.commit(); session1.close(); } catch (Exception e) { e.printStackTrace(); } } @Test public void update(){ //update方法 session2=sf.openSession(); Transaction tx2=session2.beginTransaction(); clazz=new Classes(); clazz.setName("yun"); //clazz对象被放到session缓存中,session缓存中的clazz变量指向classes对象内存。在提交事务之前数据不会被存放到数据库 //clazz和clazz2变成持久态 session2.save(clazz); clazz.setName("ru"); session2.update(clazz); tx2.commit(); session2.close(); } @Test public void GetAndDelete(){ try { //delete方法和get方法 session3=sf.openSession(); Transaction tx3=session3.beginTransaction(); //get()查询方法 Classes c=(Classes)session3.get(Classes.class, 3); System.out.println("id为"+3+"的用户:"+c.getName()+"将要被删除!!"); //delete()方法 session3.delete(c); tx3.commit(); } catch (HibernateException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ sf.close(); } } }
hibernate简单的增删改查实例
猜你喜欢
转载自tydldd.iteye.com/blog/1720161
今日推荐
周排行