Spring @Transactional没有开始交易 [英] Spring @Transactional not starting a transaction

查看:143
本文介绍了Spring @Transactional没有开始交易的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多模块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没有开始交易的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆