hibernate异常 Session was already closed

hibenate连接Sql Server异常:


public class TestMain {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
        //对数据持久层操作
        //该类主要是用于读取hibernate.cfg.xml
        Configuration cf=new Configuration().configure();
        //创建一个会话工厂.
        SessionFactory sf=cf.buildSessionFactory();
        //创建Session(会话)<->Connection
        Session s=sf.getCurrentSession();
        //开始事务
        Transaction ts=s.beginTransaction();
        //加入一个对象(记录)
        Employe employe=new Employe();
        //employe.setId(10);
        employe.setName("杨德成");
        s.save(employe);//添加该对象到数据库
        ts.commit();
        s.close();

    } catch (Exception e) {
        e.printStackTrace();
        // TODO: handle exception
    }
    }

}

运行报错:

02

出现以上原因是Session关闭

如果不是使用的SessionFactory.getSession()来获得Session。

    而是使用SessionFactory.getCurrentSession()方法来获得Session时,当事务结束的时候,不管是提交还是回滚事务,hibernate会自动关闭Session的,

所以不需要手动关闭。

发布了53 篇原创文章 · 获赞 58 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/XiNanHeiShao/article/details/75452653