Spring managed transactions @Transactional annotation

为君一笑 提交于 2019-12-11 11:02:25

问题


Propagation setting is REQUIRED.

@Transactional(propagation = Propagation.REQUIRED)

Transaction is read/write.

In which scenario those are used? Please give me explain with example


回答1:


Spring transaction default is

@Transactional(propagation = Propagation.REQUIRED)

So you do not need to specify the propagation property.

So, What does it mean by @Transactional annotation for a spring component ?

  • Spring framework will start a new transaction and executes all the method and finally commit the transaction.

  • But If no transaction is exists in the application context then spring container will start a new transaction.

  • If more than one method configured as Propagation.REQUIRED then transactional behavior assigned in a nested way to each method in logically but they are all under the same physical transaction.

So, What is the result ?
The result is if any nested transaction fail, then the whole transaction will fail and rolled back (do not insert any value in db) instead of commit.

Example:

@Service
public class ServiceA{

    @Transactional(propagation = Propagation.REQUIRED)
    public void foo(){
        fooB();
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void fooB(){
        //some operation
    }

}

Explanation : In this example foo() method assigned a transactional behavior and inside foo() another method fooB() called which is also transactional. Here the fooB() act as nested transaction in terms of foo(). If fooB() fails for any reason then foo() also failed to commit. Rather it roll back.




回答2:


This annotation is just to help the Spring framework to manage your database transaction.

Lets say you have a service bean that writes to your database and you want to make sure that the writing is done within a transaction then you use

@Transactional(propagation = Propagation.REQUIRED)

Here is a small example of a Spring service bean.

@Service
class MyService {

    @Transactional(propagation = Propagation.REQUIRED)
    public void writeStuff() {

      // write something to your database
    }   
}

The Transactional annotation tells Spring that:

  • This service method requires to be executed within a transaction.
  • If an exception gets thrown while executing the service method, Spring will rollback the transaction and no data is written to the database.


来源:https://stackoverflow.com/questions/46786651/spring-managed-transactions-transactional-annotation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!