A recent project on the official website, I have two operations on the service layer to add data, very unexpected error, and then studied the transaction
Just before you know declarative transactions and programmatic transactions, programmatic transactions can be cumbersome, typically using declarative transactions.
Spring provides many ways to configure:
Programmatic transactions:
Open a transaction;
try{
Update or add an operation;
Submitted
}catch (..) {
Roll back;
}
Declarative transactions:
Commit, rollback operations are written in a proxy class, open a transaction before executing the transaction method, commit or roll back the transaction before executing the method
1 Configure a proxy class for each bean (service class)
2 Common one proxy class for all service classes
3 Interceptors (AOP way)
4 full annotations (in service class plus transaction)
Note: Spring only rolls back (tested) for runtiomexception to provide the corresponding property set exception type
Here is the configuration of the transaction in my Project (config configuration):
/** * Annotated declarative transaction configuration (equivalent to the configuration of the AOP method described above) * @author liyong * */@Configurationpublic class Txadvicetransactionconfig {private STA Tic final String aop_pointcut_expression = "Execution (* com.mike.mihome.*.service). *.*(..))"; @Autowired private Platformtransactionmanager TransactionManager; @Bean public Transactioninterceptor Txadvice () {Namematchtransactionattributesource Source = new Namematchtransa Ctionattributesource (); Read-only transaction, do not update operation Rulebasedtransactionattribute Readonlytx = new Rulebasedtransactionattribute (); Readonlytx.setreadonly (TRUE); Readonlytx.setpropagationbehavior (transactiondefinition.propagation_not_supported); The current transaction is currently present and a new transaction is created with no transaction currently present Rulebasedtransactionattribute REQUIREDTX = new Rulebasedtransactionattribute ();// Requiredtx.setrollbackrules (Collections.singletonlist (New Rollbackruleattribute (Exception.class)));//Set Exception typeRequiredtx.setpropagationbehavior (transactiondefinition.propagation_required); Requiredtx.settimeout (10000); map<string, transactionattribute> txmap = new hashmap<string, transactionattribute> (); Txmap.put ("query*", Readonlytx); Txmap.put ("get*", Readonlytx); Txmap.put ("*", REQUIREDTX); Source.setnamemap (TXMAP); Transactioninterceptor txadvice = new Transactioninterceptor (TransactionManager, source); return txadvice; } @Bean Public Advisor txadviceadvisor () {aspectjexpressionpointcut pointcut = new Aspectjexpressionpoin Tcut (); Pointcut.setexpression (aop_pointcut_expression); return new Defaultpointcutadvisor (Pointcut, Txadvice ()); }}
Understand Spring business