@Repository
public interface BatchRepository extends CrudRepository<Batch,Integer> {}
So right here ^ for example does this spring boot annotation @Repository also automatically come with the @Transactional annotation too?
or do I need to specifically declare @Transactional?
Thank you
I don't know how to test this, and can't find any relevant documentation on this, so I'm asking stack overflow experts Haha.
CodePudding user response:
@Repository
does not automatically add @ Transactional
, you need to explicitly mention it. With the recent versions of spring, you don't need to even provide @Repository
on your BatchRepository
, Spring Boot is smart enough to automatically figure out it is the implementation of CrudRepository
and create a BatchRepository
repository bean.
@Transactional
public interface BatchRepository extends CrudRepository<Batch,Integer> {}
Should be equivalent to
@Transactional
@Repository
public interface BatchRepository extends CrudRepository<Batch,Integer> {}
I prefer to add @Transactional
in Service Layer rather than in Repository layer as Repository is outside of business context and it should not know about isolation.
CodePudding user response:
You need to declare @Transactional method where you need it by yourself. It is often done this way (or withoud autowired with lombok annotations):
@Service
public class TestService{
@Autowired
public BatchRepository batchRepository;
@Transactional
public Batch addBatch(Batch batchToInsert){
return batchRepository.save(batchToInsert);
}
}