Search code examples
springspring-bootspring-data-jpatransactional

Springboot 1.5.7 / SpringDataJPA - Why methods in repository are not all transactional by default


This code in my repository :

public interface ClientRepository extends CrudRepository<Client, Long> {

//@Transactional
@Modifying
@Query("update Client c set c.firstName = ?1, c.lastName = ?2, c.email = ?3 where c.id = ?4")
void updateClientInfoById(String firstname, String lastname, String email, Long userId);

Executing this method(updateClientInfoById) using a REST Service give me this exception : javax.persistence.TransactionRequiredException: Executing an update/delete query

I Have to add @Transactional to get it works.

why methods in repository are not all transactional by default ?

Thanks in advance :)


Solution

  • Only CRUD methods are by default marked as transactional. You are using custom query methods so you should explicitly mark it with @Transactional annotation.

    Additionally, we can get rid of the @Transactional annotation for the method as the CRUD methods of the Spring Data JPA repository implementation are already annotated with @Transactional.

    For more informations, see Getting started with Spring Data JPA

    EDIT : CRUD methods are CrudRepository methods