简体   繁体   中英

Is usage @Transactional Annotation Necessary? Spring boot

So I'm new in Spring and currently confused about @Transactional Annotation, I have read a lot of question and answer 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 can 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 not using @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 that I don't want that 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 method and changes will be flushed and committed
}

what if, at the end of the method the database goes offline, it will rollback right, you will lose all your progress right. Even tho maybe when in repository.save(te) in catch block statement the database was okay and you don't want to lose that progress. Is there any solution or idea about this?

Thanks.

  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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM