我有一个仅在mysql中调用过程的方法。这是我的代码:
import javax.persistence.EntityManager;
import javax.persistence.ParameterMode;
import javax.persistence.PersistenceContext;
import javax.persistence.StoredProcedureQuery;
import javax.transaction.Transactional;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class ClientService {
@PersistenceContext
protected EntityManager entityManager;
@Async
public void callFunction(Integer clientId) {
StoredProcedureQuery query = entityManager.createStoredProcedureQuery("myProcedureSql");
query.registerStoredProcedureParameter("clientId", Integer.class, ParameterMode.IN);
query.setParameter("clientId", clientId);
query.execute();
}
}
我需要它异步运行,但是当我将@Async标记放入方法中时,它失败,给我以下错误:
196536 [SimpleAsyncTaskExecutor-2] ERROR org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler - Unexpected error occurred invoking async method 'public void ar.com.lemondata.turnero.backend.service.PruebaService.procesarCSV()'.
org.springframework.dao.InvalidDataAccessApiUsageException: 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/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.; nested exception is 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/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
如果我删除@Async,则代码可以完美运行
答案 0 :(得分:0)
@Async
将产生一个新线程(如果未配置线程池),并且该线程不能继承父事务。因为,Spring Transaction是基于每个线程的。
如果您将@Transactional
设置为相关的传播值。这应该可以解决您的问题。
除非它非常关键,否则我不会推荐这种事务管理方式。