首页 > 代码库 > Hibernate学习(二)保存数据
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 }
Hibernate学习(二)保存数据
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。