Hibernate学习(二)保存数据

 1 package cn.lonecloud.test;
 2 
 3 import java.util.Date;
 4 
 5 import org.hibernate.HibernateException;
 6 import org.hibernate.Session;
 7 import org.hibernate.SessionFactory;
 8 import org.hibernate.Transaction;
 9 import org.hibernate.cfg.Configuration;
10 import org.junit.Before;
11 import org.junit.Test;
12 
13 import cn.lonecloud.domain.User;
14 
15 public class MyDemoTest {
16 
17     private Session session;
18 
19     private SessionFactory buildSessionFactory;
20 
21     public SessionFactory getBuildSessionFactory() {
22         return buildSessionFactory;
23     }
24 
25     public void setBuildSessionFactory(SessionFactory buildSessionFactory) {
26         this.buildSessionFactory = buildSessionFactory;
27     }
28 
29     public void setSession(Session session) {
30         this.session = session;
31     }
32 
33     @Before
34     public void getSession() {
35         Configuration cfg = new Configuration().configure();
36         setBuildSessionFactory(cfg.buildSessionFactory());
37         session= buildSessionFactory.openSession();
38     }
39     @Test
40     public void saveTest(){
41         Transaction transaction = null;
42         try {
43             transaction = session.beginTransaction();//创建session
44             User user=new User();
45             user.setName("小李");
46             user.setPassword("123");
47             user.setBirthday(new Date());
48             session.save(user);//保存操作
49             transaction.commit();//提交事务
50         } catch (HibernateException e) {
51             if (transaction!=null) {
52                 transaction.rollback();//事务回滚
53             }
54             e.printStackTrace();
55         }finally{
56             if (session!=null&&session.isOpen()) {
57                 session.close();//关闭session
58             }
59         }
60     }
61 }

 

posted @ 2016-10-16 21:09  lonecloud  阅读(1719)  评论(0编辑  收藏  举报
我的博客即将同步至 OSCHINA 社区,这是我的 OSCHINA ID:lonecloud,邀请大家一同入驻:https://www.oschina.net/sharing-plan/apply