I am still trying to wrap my head around how @Transactional works.
I have @Transactional annotation on Service class's method and @Modifying annotation on the method in the Repository class. Does method with @Transactional annotation applies to the method in the Repository with annotation @Modifying?
My understanding:
@Transactionalon a method of a class with@Transactional( readOnly = true )no data gets written to the database, whereas with@Transactional, the data gets written to the database.
Modifying Queries
- Modifying method signature can only return
void,Integerorint- Updating queries MUST be transactional, mark with
@Transactional- Spring Data will drop all non-flushed changes pending in the
EntityManager, change with@Modifying(clearAutomatically=false)
As the second point says @Modifying queries must have @Transactional(readOnly=false), so we can either add it at @Service level method call or @Repository method level call. If added at the @Service level it applies to the @Respository method too which is being called from the @Service level method call?
Example:
@Service
class AnimalServiceImpl implements AnimalService {
@Autowire
AnimalRepository animalRepository;
@Override
@Transactional
public void persistAnimal() {
....
animalRepository.save();
}
@Override
@Transactional(readOnly = true)
public void checkIfAnimalPresent() {
...
animalRepository.checkIfPresent();
}
@Override
@Transactional
public void deleteAnimal() {
...
animalRepository.deleteAnimal();
}
}
Repository
@Repository
@Transactional(readOnly=true)
public interface AnimalRepository extends org.springframework.data.repository.Repository {
@Modifying
@Query(...)
void save();
@Modifying
@Query(...)
int checkIfPresent() 
@Modifing
@Query(..)
int deleteAnimal();
}
My question is around:
- Why do we need @Transactionalin the service class when we have it at the repository@Repositorylevel and I have@Modifyingon methods which modify the entity and writes it to the database (only because I have@Transactional(readOnly = true)at the class level) ?
- Does the annotation @Transactionalon the Service class propogate to@Repositoryclass?
I hope I am very clear with my questions and examples here.
 
     
     
    