Search code examples
javaspringspring-datacrudtransactional

Is the CrudRepository .delete() method transactional?


When using Spring-data it is possible to extend the CrudRepository.

How does this Repositories .delete() method work "under the hood"?

Also, is this method Transactional? If this is the case, is there any need to use @Transactional annotations when using Spring-data.

e.g is @Transactional needed here? :

Extending CrudRepository:

public interface PersonRepository extends CrudRepository<Person, Integer> {

}

Using delete method in service class:

 @Transactional
 public void deletePerson(Person person) {

        personRepository.delete(person);
    }

Edit: How would @Transactional work here?

 @Transactional
     public void deletePersonAndTable(Person person, Table table) {

            personRepository.delete(person);

            tableRepository.delete(Table);

        }

Solution

  • You don't need to add @Transactional annotations yourself.

    From https://spring.io/blog/2011/02/10/getting-started-with-spring-data-jpa/:

    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.

    But you should add one in your DOA though, if you want to perform some actions sequently that should only be executed all together or none at all (that's what transactions are for).