获取session对象的两种方法

获取session对象的两种方法

1.openSession()
2.getCurrentSession(),此方法需要在hibernate.cfg.xml配置文件中添加 thread

以下为两种方法的代码:

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.Test;


public class SessionTest {

    @Test
    public void testOpenSession(){
        Configuration config=new Configuration().configure();//获得配置对象
        //获得服务注册对象
        ServiceRegistry serviceRegistry=new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
        //获得sessionFactory对象
        SessionFactory sessionFactory=config.buildSessionFactory(serviceRegistry);
        //获得session对象
        Session session=((SessionFactory) sessionFactory).openSession();
        if(session!=null){
            System.out.println("session创建成功");
        }
        else{
            System.out.println("session创建失败");
        }



    }

    @Test
    public void testGetCurrenSession(){
        Configuration config=new Configuration().configure();//获得配置对象
        //获得服务注册对象
        ServiceRegistry serviceRegistry=new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
        //获得sessionFactory对象
        SessionFactory sessionFactory=config.buildSessionFactory(serviceRegistry);
        //获得session对象
        Session session=((SessionFactory) sessionFactory).getCurrentSession();
        if(session!=null){
            System.out.println("session创建成功");
        }
        else{
            System.out.println("session创建失败");
        }


    }
}

你可能感兴趣的:(获取session对象的两种方法)