Spring Boot项目报错: Cause: java.lang.IllegalStateException: No thread-bound request found

1. 问题描述

在进行Spring Boot项目开发时,项目中出现一个匪夷所思的问题:项目中的一个接口,在调用其他接口完成逻辑处理后,需要将该接口返回的数据存储在数据库中(项目使用mybatis-plus进行数据库的增删改查操作),此时就出现一个问题,当采用web端调用时(前端登录系统发请求),能够正常将返回的数据插入数据库,但是采用定时任务(schedule-----@EnableScheduling)调用接口时,数据无法正常插入数据库,出现报错。

1.1 报错详情
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException: 
Error updating database.  Cause: java.lang.IllegalStateException: No thread-bound request found:
Are you referring to request attributes outside of an actual web request, or processing a request 
outside of the originally receiving thread? If you are actually operating within a web request 
and still receive this message, your code is probably running outside of DispatcherServlet: 
In this case, use RequestContextListener or RequestContextFilter to expose the current request.
The error may exist in com/vhengdata/dao/MsgLogMapper.java (best guess)
The error may involve com.vhengdata.dao.MsgLogMapper.insert
The error occurred while executing an update

2. 问题解决

2.1 尝试了很多网上的方法——设置共享线程的方式
  • 参考文章 : https://blog.csdn.net/sihuanghou/article/details/120760406

尝试了多次,但是还是无法解决当前问题。。。。。。。。

2.2 自己尝试的方法—— 手写sql

由于本项目采用的mybatis-plus框架,在起初直接调用框架的mapper.insert(T model)接口,考虑到可能是框架存在的问题,就自己写了个插入数据库的sql。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.test.dao.MsgLogMapper">

    <insert id="save" parameterType="com.test.model.MsgLog" >
        insert into msg_log(id,unit_id,contact_name,contact_tel,content,send_time,sms_code,response_body,unit,creater,create_id,create_date,update_id,update_date) 
        values (#{msgLog.id},#{msgLog.unitId},#{msgLog.contactName},#{msgLog.contactTel},#{msgLog.content},#{msgLog.sendTime},#{msgLog.smsCode},
                #{msgLog.responseBody},#{msgLog.unit},#{msgLog.creater},#{msgLog.createId},#{msgLog.createDate},#{msgLog.updateId},#{msgLog.updateDate})
    </insert>
</mapper>
@Mapper
public interface MsgLogMapper extends BaseMapper<MsgLog> {
    
    

    int save(@Param("msgLog")MsgLog msgLog);
}

写完成通过定时任务调用,发现数据成功插入了。

但是也不知道具体是什么原因导致的,可能是框架自身的问题,有能解决的可以留言。

猜你喜欢

转载自blog.csdn.net/qq_42102911/article/details/129054589