问题描述
我有一个多模块Maven项目,其结构如下:
I have a multi-module Maven project with the following structure:
project
|
-- data
|
-- DepartmentRepository.java
|
-- domain
|
-- Department.java
|
-- service
|
-- DepartmentService.java
|
-- DepartmentServiceImpl.java
|
-- web
|
-- DepartmentController.java
该项目使用Spring 4.1.4,Spring Data JPA 1.7.2和Maven 3.1.0.包括以下类别:
The project uses Spring 4.1.4, Spring Data JPA 1.7.2 and Maven 3.1.0. The following classes are included:
@Entity class Department {}
interface DepartmentRepository extends JpaRepository<Department, Long> {}
interface DepartmentService {
List<Department> getAll();
}
@Service
@Transactional(readOnly = true)
class DepartmentServiceImpl implements DepartmentService {
@Autowired
private DepartmentRepository departmentRepository;
@Transactional
public List<Department> getAll() {
return departmentRepository.findAll();
}
}
我希望一旦代码输入DepartmentServiceImpl.getAll
,交易就会开始.但是,我发现事实并非如此.没有事务开始.我已经通过检查此方法内部的TransactionSynchronizationManager.isActualTransactionActive()
进行了检查,该方法会打印false
.我还通过在TransactionAspectSupport.invokeWithinTransaction
中放置断点来进行检查.但是,一旦调用departmentRepository.findAll
,就可以正确启动事务(由于SimpleJpaRepository
,提供JPA存储库接口实现的类也用@Transactional
注释).
I was hoping that as soon as the code enters DepartmentServiceImpl.getAll
, a transaction would have been started. However, I am finding that this is not the case. No transaction is started. I have checked this by examining TransactionSynchronizationManager.isActualTransactionActive()
inside this method, which prints false
. I have also checked by putting break points in TransactionAspectSupport.invokeWithinTransaction
. However, as soon as departmentRepository.findAll
is invoked, a transaction is correctly started (since SimpleJpaRepository
, the class which provides an implementation of the JPA repository interface is also annotated with @Transactional
).
可以在 Github 上找到演示该问题的完整示例应用程序.
A complete sample application demonstrating the problem is available on Github.
推荐答案
我注意到您的annotation-driven
模式设置为aspectj
I noticed your annotation-driven
mode is set to aspectj
<transaction:annotation-driven mode="aspectj"/>
,但是您似乎没有 load-time-weaver
在您的上下文中的任何位置定义.
but you don't seem to have load-time-weaver
defined anywhere in your context.
这可能是问题,也可能不是问题,因为我只是快速浏览了一下.另外,我不明白为什么您需要使用aspectj
而不是默认的proxy
模式,因此完全删除mode="aspectj"
并默认使用代理即可.
That may or may not be the issue as I only took a quick look. Also, I don't see why you would need aspectj
vs the default proxy
mode with what you have, so you might be fine just removing the mode="aspectj"
altogether and default to proxy.
这篇关于Spring @Transactional没有开始交易的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!