Hibernate 基本CRUD

 
  1 // 查询所有 
  2 @Test
  3 public void finall(){
  4     Session session = null;
  5     Transaction tx = null;
  6 
  7     session = HibernateUtil.getSession();
  8     tx = session.beginTransaction();
  9     Query<Student> query = session.createQuery("from Student");
 10     List<Student> list = query.getResultList();
 11     for (Student stu : list) {
 12         System.out.println(stu);
 13     }
 14     tx.commit();
 15 }
 16 // 根据ID查询
 17 @Test
 18 public void findByID() {
 19     Session session = null;
 20     Transaction tx = null;
 21 
 22     try {
 23         session = HibernateUtil.getSession();
 24         tx = session.beginTransaction();
 25         Student student = (Student) session.get(Student.class, 2);
 26         System.out.println(student);
 27         tx.commit();
 28     } catch (HibernateException e) {
 29         tx.rollback();
 30         e.printStackTrace();
 31     } finally {
 32         if (session != null) {
 33             session.close();
 34         }
 35     }
 36 }
 37 
 38 // 保存
 39 @Test
 40 public void save() {
 41     // 创建保存对象
 42     Student stu = new Student();
 43     stu.setName("成龙");
 44     stu.setAge(122);
 45     stu.setBirthday(new Date());
 46 
 47     Session session = null;
 48     Transaction tx = null;
 49 
 50     try {
 51         session = HibernateUtil.getSession();
 52         tx = session.beginTransaction();
 53         //session.save(stu);
 54         session.save(stu);
 55         tx.commit();
 56     } catch (HibernateException e) {
 57         tx.rollback();
 58         e.printStackTrace();
 59     } finally {
 60         if (session != null) {
 61             session.close();
 62         }
 63     }
 64 }
 65 
 66 // 更新
 67 @Test
 68 public void update() {
 69     Session session = null;
 70     Transaction tx = null;
 71 
 72     try {
 73         session = HibernateUtil.getSession();
 74         tx = session.beginTransaction();
 75         Student student = (Student) session.get(Student.class, 2);
 76         student.setName("金亚荣");
 77         student.setAge(11);
 78         session.saveOrUpdate(student);
 79         tx.commit();
 80     } catch (HibernateException e) {
 81         tx.rollback();
 82         e.printStackTrace();
 83     } finally {
 84         if (session != null) {
 85             session.close();
 86         }
 87     }
 88 }
 89 // 删除 
 90 @Test
 91 public void Delete(){
 92     Session session = null;
 93     Transaction tx = null;
 94 
 95     session = HibernateUtil.getSession();
 96     tx = session.beginTransaction();
 97     Student stu = session.get(Student.class, 2);
 98     session.delete(stu);
 99     tx.commit();
100 }
101 }

 

posted @ 2016-11-24 20:38  yura93  Views(113)  Comments(0)    收藏  举报