org.hibernate.HibernateException: No CurrentSessionContext configured!

今天在测试的时候遇到了org.hibernate.HibernateException: No CurrentSessionContext configured!错误。。。找了半天,在百度上才发现是什么原因。。。
初学hibernate,出现No CurrentSessionContext configured错误,检查了几次配置都没有发现问题,最后上网查找发现是配置文件的问题
解决如下:
在集成Hibernate的环境下(例如Jboss),在hibernate.cfg.xml中session-factory段加入:
[color=red]<property name="current_session_context_class">jta</property>[/color]
在不集成Hibernate的环境下(例如使用JDBC的独立应用程序),在hibernate.cfg.xml中session-factory段加入:
[color=red]<property name="current_session_context_class">thread</property>[/color]
加入了这句话什么测试类就可以运行了。。。。哎,这个错误我来记录下
package org.huawei.hibernate.junit;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.huawei.hibernate.Teacher;
import org.huawei.hibernate.zhicheng;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

/**
* @作者: 何枫
* @日期: 2011-4-10下午11:57:04
* @版本: V 1.0
* @标题: SaveTest.java
* @包名: org.huawei.hibernate.junit
* @描述: TODO(用一句话描述该文件做什么)
*/
public class SaveTest {
private static SessionFactory sessionFactory;

@BeforeClass
public static void beforeClass() {
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
}
@AfterClass
public static void afterClass() {
sessionFactory.close();
}
@Test
public void testSaveWith3State() {

Teacher t = new Teacher();

t.setName("何枫");
t.setTitle("middle");
t.setZhicheng(zhicheng.A);
//t.setBirthDate(new Date());
t.setDate(new Date());
//Session session = sessionFactory.openSession();
/*
* 在使用sessionFactory.getCurrentSession()是必须在hibernate的配置文件中加入
* <property name="current_session_context_class">thread</property>
*/
/**
* openSession与getCurrentSession的区别是:
* openSession每次都是新的,需要close
* getCurrentSession从上下文找,如果有,用旧的,如果没有,建新的
* 1.用途,界定事务边界
* 2.事务提交自动close
*/
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
session.save(t);
System.out.println(t.getId());
session.getTransaction().commit();
//session.clear();
System.out.println(t.getId());
}


public static void main(String[] args) {
beforeClass();
}
}

终于搞定了.学习软件开发是需要日积月累的。。。。更应正了一句最经典的话,,程序员是在错误中长大的!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值