单例模式的SessionFactory与getCurrentSession()的使用



getCurrentSession()获得的session的好处。 
(1)currentSession和当前线程绑定。 
(2)currentSession在事务提交后自动关闭

1.hibernate.cfg.xml 中添加的配置

<property name="hibernate.current_session_context_class">thread</property>

2.demo1实现SessionFactory


  private static SessionFactory factory;

    // 静态初始化块,加载配置信息,获取SessionFactory
    static {
        // 读取hibernate.cfg.xml文件
        Configuration cfg = new Configuration().configure();
        // 建立SessionFactory
        factory = cfg.buildSessionFactory();
    }

    public static SessionFactory getSessionFactory() {
        return factory;
    }
2.Test类

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import domain.user;

public class Test {
public static void main(String[] args) {
SessionFactory factory =demo1.getSessionFactory();
//getCurrentSession()生成的session会自动关闭 ,在事务提交之后
Session session=factory.getCurrentSession();
user user=new user();
user.setId(1);
user.setUsername("王某");
user.setPassword("666666");
   Transaction transaction =null;
   
    try {
transaction =session.beginTransaction();
session.save(user);
//session.delete(user);删除
//user  select =session.find(user.class,1);查找
//session.update(user);修改
   transaction.commit();
} catch (Exception e) {
// TODO: handle exception
if(transaction !=null){
transaction.rollback();
}
e.printStackTrace();
}
}

}

3.测试结果

单例模式的SessionFactory与getCurrentSession()的使用