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.current_session_context_class=thread
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;
}
<tx:annotation-driven transaction-manager="transactionManager"
proxy-target-class="true" />共同进步,多谢指正!

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

被折叠的 条评论
为什么被折叠?



