您的位置:首页 > 其它

hibernate框架中附带提交事务的方法getCurrentSession()

2017-09-21 09:18 459 查看
1.创建session工厂

public class HibernateUtil {

private static SessionFactory sf ;

public static SessionFactory getSessionFactory(){
Configuration cfg = new Configuration();
cfg.configure();  //加载解析 hibernate.cfg.xml

StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
builder.applySettings(cfg.getProperties());
ServiceRegistry sr = builder.build();

sf = cfg.buildSessionFactory(sr);
return sf;
}

}

2.创建session两种方式:

SessionFactory fs = HibernateUtil.getSessionFactory();

Session ss=null;
Transaction tr = null;

try{
ss = fs.openSession();//通过sessionFactory获得一个session对象  session == connection
tr = ss.getTransaction();
tr.begin();
ss.save(stu);
tr.commit();
}catch (HibernateException e) {
// TODO: handle exception
e.printStackTrace();
}finally{
if(ss != null){
ss.close();
}
}

如果是ss=fs.getCurrentSession(),则不需要手动处理事务,当创建session的时候会检查前面是否有session,有就返回原来的session对象

而openSession()每次创建都会创建新的session对象,且需要手动提交事务

eg. ses1=fs.getCurrentSession()  ses2=fs.getCurrentSession()

ses1==ses2--------true

如果中途提交事务则原来的session会被销毁,重新创建session 

ses1==ses2---------false
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐