猿问

getCurrentSession得到session对象配置

 JUit报错:

org.hibernate.HibernateException: No CurrentSessionContext configured!

hibernate.cfg.xml配置文件已经配置了:

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

测试文件:

package Student;

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.After;
import org.junit.Test;

public class SessionTest {

 @Test
 public void testopenSession() {
  //1.创建配置对象
  Configuration config=new Configuration().configure();
  //2.创建服务配置对象
  ServiceRegistry serviceRegistry=new ServiceRegistryBuilder().
    applySettings(config.getProperties()).buildServiceRegistry();
  //3.创建会话工厂
  SessionFactory sessionFactory=config.buildSessionFactory(serviceRegistry);
  //4.打开会话
  Session session=sessionFactory.openSession();
  if(session!=null)
  {
   System.out.print("session创建成功");
  }else{
   System.out.print("session创建失败");
  }
 }
 
 @Test
 public void testgetCurrentSession() {
  //1.创建配置对象
    Configuration config=new Configuration().configure();
    //2.创建服务配置对象
    ServiceRegistry serviceRegistry=new ServiceRegistryBuilder().
      applySettings(config.getProperties()).buildServiceRegistry();
    //3.创建会话工厂
    SessionFactory sessionFactory=config.buildSessionFactory(serviceRegistry);
  //4.获得会话
  Session session2 =sessionFactory.getCurrentSession();
  if(session2!=null)
  {
   System.out.print("session创建成功");
  }else{
   System.out.print("session创建失败");
  }
 }
}

 

求大神指点这里是哪里错误

黄森huang
浏览 1674回答 2
2回答

慕粉4075985

要用getCurrentSession();需要在hibernate.cfg.xml 配hibernate.current_session_context_class =thread
随时随地看视频慕课网APP

相关分类

Java
我要回答