Spring @Transactional not starting a transaction

戏子无情 提交于 2019-12-25 01:32:58

问题


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

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();
  }
}

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).

A complete sample application demonstrating the problem is available on Github.


回答1:


I noticed your annotation-driven mode is set to aspectj

<transaction:annotation-driven mode="aspectj"/>

but you don't seem to have load-time-weaver defined anywhere in your context.

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.



来源:https://stackoverflow.com/questions/28696152/spring-transactional-not-starting-a-transaction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!