Hibernate事务代码规范写法
1 代码结构
try {
开启事务
提交事务
}catch() {
回滚事务
}finally {
关闭
}
实例:
1 @Test 2 3 public void testTx() { 4 5 SessionFactory sessionFactory = null; 6 7 Session session = null; 8 9 Transaction tx = null;10 11 try {12 13 sessionFactory = HibernateUtils.getSessionFactory();14 15 session = sessionFactory.openSession();16 17 //开启事务18 19 tx = session.beginTransaction();20 21 22 23 //添加24 25 User user = new User();26 27 user.setUsername("崔斌");28 29 user.setPassword("110010");30 31 user.setAddress("山东青岛");32 33 34 35 session.save(user);36 37 38 39 int i = 10/0;40 41 //提交事务42 43 tx.commit();44 45 }catch(Exception e) {46 47 e.printStackTrace();48 49 //回滚事务50 51 tx.rollback();52 53 }finally {54 55 //关闭操作56 57 session.close();58 59 sessionFactory.close();60 61 }62 }