现在的位置: 首页 > 综合 > 正文

org.hibernate.HibernateException: No CurrentSessionContext configured!

2017年12月26日 ⁄ 综合 ⁄ 共 2186字 ⁄ 字号 评论关闭

public class StudentManagerAdd implements StudentManager {

 public void addStudent(Student student) {
  Session session=null;
  try {
   //通过工具类HibernateSessionFactory的方法getSessionFactory()获取Session
   session=HibernateSessionFactory.getSessionFactory().getCurrentSession();
   session.beginTransaction();
   session.save(student);
   Inform inform =new Inform();
   inform.setType("新报名");
   inform.setDetail("身体健康");
   inform.setTime(new Date());
   //把对象inform通过管理对象logManageraocung起来
   InformManager logManager=new InformManagerAdd();
   logManager.addInform(inform);
   session.getTransaction().commit();
   
  } catch (Exception e) {
   System.out.println("添加失败");
   e.printStackTrace();
   
   session.getTransaction().rollback();
  }
  
 }

}

public class Client {

 public static void main(String[] args) {
  Student student=new Student();
  
  student.setName("cjg");
  
  StudentManager studentManager=new StudentManagerAdd();
  
  studentManager.addStudent(student);
 }
}

 

 

添加失败
org.hibernate.HibernateException: No CurrentSessionContext configured!
 at org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:620)
 at Impl.StudentManagerAdd.addStudent(StudentManagerAdd.java:19)
 at client.Client.main(Client.java:16)
Exception in thread "main" java.lang.NullPointerException
 at Impl.StudentManagerAdd.addStudent(StudentManagerAdd.java:35)
 at client.Client.main(Client.java:16)

 

<session-factory>
 <property name="current_session_context_class">thread</property>
 <property name="dialect">
  org.hibernate.dialect.SybaseDialect
 </property>
 <property name="connection.url">
  jdbc:jtds:sqlserver://localhost:1433;databaseName=jsdata
 </property>
 <property name="connection.username">sa</property>
 <property name="connection.password">123</property>
 <property name="connection.driver_class">
  net.sourceforge.jtds.jdbc.Driver
 </property>
 <property name="myeclipse.connection.profile">jsdata</property>
 <mapping resource="entity/Inform.xml" />
 <mapping resource="entity/Student.xml" />

</session-factory>

解释:获得连接的方式如果是HibernateSessionFactory.getSessionFactory().getCurrentSession(); 的话,则要在hibernate中设置属性<property name="current_session_context_class">thread</property> 一定是thtead,如果是getSession()的话,则配置为<property name="current_session_context_class">jta</property>

抱歉!评论已关闭.