一 如何获得session对象
1、openSession
2、getCurrentSession
二 用openSession获得session对象
1、代码
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 serviceRegistery = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
// 创建会话工厂对象
SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistery);
// 创建会话对象
Session session = sessionFactory.openSession();
if(session!=null){
System.out.println("session创建成功!");
}
else{
System.out.println("session创建失败!");
}
}
}
2、运行结果
session创建成功!
三 用getCurrentSession获得session对象
1、代码
<property name="hibernate.current_session_context_class">threadproperty>
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 testGetCurrentSession(){
// 创建配置对象
Configuration config = new Configuration().configure();
// 创建服务注册对象
ServiceRegistry serviceRegistery = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
// 创建会话工厂对象
SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistery);
// 创建会话对象
Session session = sessionFactory.getCurrentSession();
if(session!=null){
System.out.println("getCurrentSession创建成功!");
}
else{
System.out.println("getCurrentSession创建失败!");
}
}
}
2、运行结果
getCurrentSession创建成功!