The propagation properties of a thing:
When a transaction method is called by another transaction method, you must specify how the transaction should propagate. For example: The method may continue to run in an existing transaction (REQUIRED), or it may open a new transaction and run in its own transaction (REQUIRED_NEW).
The propagation behavior of a transaction can be specified by the Propagation property (propagation). Spring defines 7 kinds of propagation behavior.
Here's the main understanding of required and required_new.
Use examples to illustrate:
For example, a customer to buy two books, but the balance of the account can only buy a book, then what should be done? The way to deal with this is: 1 buy a book, 2 or two don't buy together
Code Description:
The interface for a customer to buy multiple books:
Package com.jeremy.springTransaction; Import java.util.List; Public Interface Cashier { void checkOut (String username,list<string> ISBNs);}
Implementation class:
Packagecom.jeremy.springTransaction;Importjava.util.List;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.stereotype.Service;Importorg.springframework.transaction.annotation.Transactional; @Service Public classCashierimplImplementsCashier {@Autowired Bookshopserviceimpl Bookshopserviceimpl; @Transactional @Override Public voidCheckOut (String userName, list<string>ISBNs) { //TODO auto-generated Method Stub for(String Isbn:isbns) {bookshopserviceimpl.purchase (UserName, ISBN); } }}
Purchase () method code:
@Autowired private Bookshopdao Bookshopdao; @Transactional @Override public void
Purchase (string Username, String ISBN) { // 1. Get the unit price of the book int prices = BOOKSHOPDAO.FINDBOOKPRICEBYISBN (ISBN); // Bookshopdao.updatebookstock (ISBN); // 3. Update user balances Bookshopdao.updateuseraccount (username, price); }
Full code download here:
Here's just an example.
When a customer needs to buy two books, it is necessary to call the checkout () method and start the transaction (TX1), but the checkout () method needs to call the purchase () method, and this method also has a transaction (TX2). At this point tx2 whether to reopen a transaction or put it in a TX1 transaction
When placed on a transaction TX1 run: That is, the Propagation property (propagation=required) of the transaction, the running process is as follows:
REQUIRED: Running within an existing transaction, committing together
So at this time the customer can not buy a book, because the transaction TX2, TX3 and transaction tx1 together to submit
When a transaction is reopened: that is, the Propagation property (propagation=required_new) of the transaction, the running process is as follows:
Equires_new. It means that the method must start a new transaction and run within its own transaction. If a transaction is running, you should suspend it first.
So then the customer can buy a book, because the transaction TX2 has been submitted,
Spring's act of spreading things