Reputation: 131
So I'm new in Spring and currently confused about the @Transactional
Annotation, I have read a lot of questions and answers about this topic and it seems I still don't get it.
And here is my question:
Do you need @Transactional
Annotation when performing insert update delete? when I was trying to prove that, I could still perform insert and update. Do you have any idea why that's happened?
Is there any performance benefit or issue if you use or do not use @Transactional
Annotation? Like connection management.
What will happen if I don't use @Transactional
Annotation in my program?
In my experience using @Transactional
, the update query will be flushed and committed after the method is finished, and I have some cases in which I don't want that to happen. For example:
@Transactional
private void doSomething() {
TransactionEntity te = te.findById("");
try {
//fetch using feign and throw customTimCustomTimeoutException
} catch (CustomTimeoutException e) {
te.workflowFailure("doSomething");
repository.save(te);
}
//validation
//business logic
//save this save that
//end of the method and changes will be flushed and committed
}
what if at the end of the method, the database goes offline, it will roll back right, and you will lose all your progress right? Even though maybe when in repository.save(te)
in the catch block statement the database was okay and you don't want to lose that progress. Is there any solution or idea about this?
Upvotes: 11
Views: 9443
Reputation: 1485
@Transactional
for CRUD operations when you use CrudRepository
interface. All those methods are transactional by default. I guess you were using this one. Check out https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#transactions@Transactional(readOnly = true)
for the reading methods. Look, for example, at SimpleJpaRepository.@Transactional
in the other cases otherwise you'll get "java.lang.IllegalStateException: No transactional EntityManager available".Upvotes: 6