1 //首先获得SessionFactory的对象 2 SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); 3 //然后获得session的对象 4 Session s = sessionFactory.openSession(); 5 //其次获得Transaction的对象 6 Transaction transaction = s.beginTransaction(); 7 //执行相关的数据库操作:增、删、改、查; 8 session.save(user); 9 session.delete(user); 10 session.update(user); 11 Query<R> query = session.createQuery("from User");//查询 12 List list = query.list(); 13 //提交事务 14 transaction.commit(); 15 //如果有异常,我们还要作事务的回滚,恢复到操作之前; 16 transaction.rollback(); 17 //最后还要关闭session释放资源; 18 session.close();