spring+hibernate进行线程操作时异常:save is not valid without active transaction

本文探讨了在使用Spring框架时遇到的Hibernate无有效事务异常问题,并提供了详细的解决方案,包括手动开启事务的方法。

org.hibernate.HibernateException:save is not valid without active transaction


出现异常的原因:当前的线程没有有效的事务。

线程管理类

import javax.annotation.Resource;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class RegistThreadPool {

	private StudentService studentService;
	private ThreadPoolTaskExecutor registThreadPool;
	
	public boolean reg(Student student){
			registThreadPool.execute(new RegistJob(student,studentService));

	class RegistJob implements Runnable{
		StudentService service = null;
		Student student=null;
		public RegistJob(Student student,StudentService service) {
			this.student = student;
			this.service = service;
		}

		public void run() {			
				service.save(student);
		}
	}
	
	@Resource(name="threadPool")
	public void setRegistThreadPool(ThreadPoolTaskExecutor registThreadPool) {
		this.registThreadPool = registThreadPool;
	}
	@Resource
	public void setStudentService(StudentService studentService) {
		this.studentService = studentService;
	}
}


hibernate session配置

hibernate.current_session_context_class=thread


DAO实现

	public Serializable save(T entity) {
		return  getSessionFactory().getCurrentSession().save(entity);
	}

异常出现的原因,是DAO操作中,线程与当前session的绑定,及事务是否打开。

在spring中,因为已经配置为打开事务,一般情况下是不用自己去手动打开事务支持的,这里出现需要手动打开事务的原因我也不知道(有待了解)。

解决:自己手动打开事务

	public Serializable save(T entity) {
		//return  getSessionFactory().getCurrentSession().save(entity);
		/*
		 * 手动打开事情提交
		 */
		Session session = getSessionFactory().getCurrentSession();
		Transaction tx = session.beginTransaction();
		Serializable tem = session.save(entity);
		tx.commit();
		return tem;
	}


附上spring事务配置:

	<tx:annotation-driven transaction-manager="transactionManager"
		proxy-target-class="true" />

共同进步,多谢指正!



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值