No Hibernate Session bound to thread...问题解决

本文详细阐述了在使用Spring MVC框架时,如何正确配置事务注解以确保Service层的方法能正常执行数据库操作。通过将事务注解配置到正确的Spring配置文件中,避免了No Hibernate Session bound to thread错误。文章提供了具体示例代码,并讨论了解决方案的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

报错代码:

return people;
        try {
            String hql = "select id,name,age,gender,address,crimerecord,idno,pic from escapedpeopletbl where idno=?";
            SQLQuery query2 = sessionFactory.getCurrentSession().createSQLQuery(hql).addEntity(People.class);
            query2.setString(0, idno);
            People people2 = (People)query2.uniqueResult();
            return people2;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return null;
当运行sessionFactory.getCurrentSession()时候报错:“No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here ”

解决方法:

  我用的是spring MVC来实现的,而spring MVC在实现的过程当中需要两个配置文件,第一个配置文件名称通常叫做:applicationContext.xml,第二个配置文件是用来定义 Spring MVC的模板文件的。
我将 annotation定义事务

Java代码  收藏代码

  1. <!-- 使用annotation定义事务 -->  

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


的配置写在了 applicationContext.xml 文件中,因此我在 Service 层中的事物注解

Java代码  收藏代码

  1. @Transactional  


并没有起作用。

只需要将 annotation定义事务 的配置写在第二个Spring的配置文件中,问题就解决了!!!
感谢回复我的兄弟们,以后大家配置的时候千万要注意才行啊!!!

注意:在service 中加@Transactional ,不加这个,也找不到事务,也会报这个错。        

附Service层代码:

package com.baple.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.wy.android.dao.PeopleDao;
import com.baple.model.People;
@Service
@Transactional
public class PeopleServiceImpl implements PeopleService {

    @Autowired
    PeopleDao peopleDaoImpl;
    @Transactional(readOnly=true)
    public People get(String idno) {
        return peopleDaoImpl.get(idno);
    }
    @Transactional(readOnly=true)
    public String getString(String idno) {
        return peopleDaoImpl.getString(idno);
    }

}

参考链接:http://www.iteye.com/problems/73211


转载于:https://my.oschina.net/u/1161889/blog/413524

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值