首页 > 代码库 > Hibernate框架增删改查测试类归为一个类

Hibernate框架增删改查测试类归为一个类

  1 package cn.happy.test;  2   3   4 import org.hibernate.Session;  5 import org.hibernate.SessionFactory;  6 import org.hibernate.Transaction;  7 import org.hibernate.cfg.Configuration;  8 import org.junit.After;  9 import org.junit.Before; 10 import org.junit.Test; 11  12 import cn.happy.entity.Student; 13 import cn.happy.util.HibernateUtil; 14  15 public class H_01Test { 16     Session session; 17     Transaction tx;  18      public static void main(String[] args) { 19        Class clazz=Student.class; 20        System.out.println(clazz); 21      } 22       23      @After 24      public void afterTest(){ 25          tx.commit(); 26          HibernateUtil.closeSession(); 27      } 28       29      @Before 30      public void initData(){ 31          session = HibernateUtil.getSession(); 32          tx= session.beginTransaction(); 33      } 34       35      /** 36          * 1.3  用get方法查询 37          */ 38         @Test 39         public void getTest(){ 40              Student stu=(Student)session.get(Student.class, 3); 41              System.out.println(stu); 42              43         } 44       45      46     /** 47      * 1.2 修改学生  48      */ 49     @Test 50     public void updateTest(){ 51          Session session = HibernateUtil.getSession(); 52           53          //不被上下文跟踪对象  54          /*Student stu=new Student(); 55          stu.setId(3); 56          stu.setName("微冷的雨训练营");*/ 57           58          //方式二:如何用呗上下文跟踪的方式 59          //检索出一条记录,一个实体对象 60          Student stu= (Student)session.load(Student.class,3); 61          stu.setName("金龙加油!!!!"); 62  63          Transaction tx = session.beginTransaction(); 64          session.update(stu); 65          tx.commit(); 66          HibernateUtil.closeSession(); 67          System.out.println("update ok!"); 68     } 69      70      71     /** 72      * 1.1 删除学生  73      */ 74     @Test 75     public void delTest(){ 76          77          Student stu=new Student(); 78          stu.setId(2); 79          session.delete(stu); 80          81          System.out.println("del ok!"); 82     } 83      84      85     /** 86      * 1.0 添加学生 87      */ 88   @Test 89   public void testAdd(){ 90       //1.1构建一个学生对象 91       Student stu=new Student(); 92       stu.setAge(18); 93       stu.setName("2016年8月28日09:21:09训练营"); 94       stu.setId(3); 95        96       //1.2 找到和数据库的接口      xxx========session--->sessionFactory--->configure.buildSessionFactory() 97       //咱们要想打通和db通道 98       Configuration cf=new Configuration().configure("hibernate.cfg.xml"); 99       SessionFactory factory = cf.buildSessionFactory();100       Session session = factory.openSession();101       Transaction tx = session.beginTransaction();102 103       //1.3保存   104       session.save(stu);105       tx.commit();106       session.close();107   }108     109 }

 

Hibernate框架增删改查测试类归为一个类