mardi 24 février 2015

Spring @Transactional not starting a transaction

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.


Aucun commentaire:

Enregistrer un commentaire