Willy Setiawan
Willy Setiawan

Reputation: 131

Is usage @Transactional Annotation Necessary? Spring boot

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:

@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

Answers (1)

jwpol
jwpol

Reputation: 1485

  1. You don't need @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
  2. Performance benefit appears when you mark the method as @Transactional(readOnly = true) for the reading methods. Look, for example, at SimpleJpaRepository.
  3. Only CRUD operations are by default transactional. You have to use @Transactional in the other cases otherwise you'll get "java.lang.IllegalStateException: No transactional EntityManager available".
  4. It depends what kind of exception you'll get. If it's runtime you'll get rollback agree. However, if it's a checked exception you can catch it and decide if you want to flush the data anyway. If you have some heavy operations on the DB and you don't want to lose this progress, you can eventually flush multiple times, it depends on the use case.

Upvotes: 6

Related Questions