//初始化
Configuration conf=null;
SessionFactory sf=null;
Session session=null;
Transaction tx=null;
try{
//1.获取配置
conf=new Configuration().configure();
//2.获取session工厂
sf=conf.buildSessionFactory();
//3.获取session
session=sf.openSession();
//4.获取事务
tx=session.beginTransaction();
tx.begin();
//创建学生对象
Student stu=new Student();
// stu.setStuname("kevin");
// stu.setStudate(new Date());
stu.setStuname("russell");
stu.setStudate(new Date());
//5.持久化
session.save(stu);
//6.提交事务
tx.commit();
}catch(HibernateException e){
e.printStackTrace();
//6.事务回滚
tx.rollback();
}finally{
//7.关闭session
session.close();
sf.close();
}
![](https://img2024.cnblogs.com/blog/35695/202408/35695-20240826070647288-243310440.jpg)