Using the annotation @Transactional
spring executes the function past the repository save error to the following lines that shouldn't have been executed!!
Example: Using @Transactional
on method
iEmployeeRepository.save(employee); <<-- Error occurs here
System.out.println("Hello"); <<-- This line still gets executed
I know @Transactional
behaviour doesn't need a save, it automatically updates the ORM entity, according to this behaviour it looks like its running all the code and executes save repository by itself after all function code has run.
How can make sure @Transactional
stop executing code when an error occurs when save repository is called?
CodePudding user response:
save
doesn't throw an exception. Due to JPAs write cache SQL statements are moved back as far as possible, which often mean to the end of the transaction, at which time all the collected changes will be flushed to the database. Any exceptions caused by that interaction will be raised at that time only.
This is JPA behaviour and independent of Spring.
You can avoid this by using JpaRepository.saveAndFlush(..)
This will force a flush
right after the save
and thereby trigger all errors early.