当前位置:网站首页>Day10: declarative transaction control
Day10: declarative transaction control
2022-07-24 21:55:00 【Zhuowen】
Declarative transaction control
Programming transactions control related objects ( understand )
PlatformTransactionManager
PlatformTransactionManager Interface is spring Transaction manager for , It provides our common methods of operating transactions .
| Method | explain |
|---|---|
| TransactionStatus getTransaction(TransactionDefination defination) | Get the status information of the transaction |
| void commit(TransactionStatus status) | Commit transaction |
| void rollback(TransactionStatus status) | Roll back the transaction |
Be careful :
PlatformTransactionManager It's the interface type , Different Dao Layer technology has different implementation classes ,
for example :
Dao Layer technology is jdbc or mybatis when :org.springframework.jdbc.datasource.DataSourceTransactionManager
Dao Layer technology is hibernate when :org.springframework.orm.hibernate5.HibernateTransactionManager
So we need to configure the following configuration to tell spring Framework what we use Dao Layer technology
TransactionDefinition
TransactionDefinition yes Transaction definition information object , Internally encapsulate the parameters of the transaction definition , It has the following methods :
| Method | explain |
|---|---|
| int getIsolationLevel() | Get the isolation level of the transaction |
| int getPropogationBehavior() | Get the propagation behavior of transactions |
| int getTimeout() | Get timeout |
| boolean isReadOnly() | Is it read-only |
1. Transaction isolation level
Set isolation level , It can solve the problem of transaction concurrency , Dirty reading 、 It can't be repeated or unreadable ( Fantasy reading ).
- ISOLATION_DEFAULT
- ISOLATION_READ_UNCOMMITTED
- ISOLATION_READ_COMMITTED
- ISOLATION_REPEATABLE_READ
- ISOLATION_SERIALIZABLE
2. Transaction propagation behavior
- REQUIRED: If there is no current transaction , Just create a new transaction , If there is already a transaction , Join in the business . General choice ( The default value is )
- SUPPORTS: Support current transaction , If there is no current transaction , Just in a non transactional way ( No transaction )
- MANDATORY: Use the current transaction , If there is no current transaction , Throw an exception
- REQUERS_NEW: New transaction , If you are currently in a transaction , Suspend current transaction .
- NOT_SUPPORTED: Perform operations in a non transactional way , If there are currently transactions , Suspend the current transaction
- NEVER: Run in a non transactional manner , If there are currently transactions , Throw an exception
- NESTED: If there are currently transactions , Within the nested transaction . If there is no current transaction , execute REQUIRED Similar operation
- Timeout time : The default value is -1, There is no timeout limit . If there is , Set in seconds
- Is it read-only : It is recommended to set the query to read-only
TransactionStatus
TransactionStatus What the interface provides is The specific running state of the transaction , The method is introduced as follows .
| Method | explain |
|---|---|
| boolean hasSavepoint() | Whether to store rollback points |
| boolean isCompleted() | Whether the transaction is complete |
| boolean isNewTransaction() | Whether it's a new business |
| boolean isRollbackOnly() | Whether the transaction is rolled back |
Knowledge points
Programming transactions control three objects
- PlatformTransactionManager
- TransactionDefinition
- TransactionStatus
be based on XML Declarative transaction control for
What is declarative transaction control
Spring Declarative transactions, as the name suggests, are Handle transactions declaratively . The statement here , It means to declare... In the configuration file , Use in Spring The declarative transaction processing in the configuration file replaces the code processing transaction .
The role of declarative transactions :
- Transaction management does not invade the developed components . say concretely , Business logic objects don't realize that they're managing transactions , In fact, it should be like
this , Because transaction management is a system level service , Not part of the business logic , If you want to change the business management plan , You just need to reconfigure it in the definition file - When you don't need transaction management , Just modify the settings file , You can remove the transaction management service , Recompile without changing the code , It's extremely convenient to maintain
Be careful :Spring The bottom layer of declarative transaction control is AOP.
Implementation of declarative transaction control
Declarative transactions control explicit matters :
- Who is the cut point ? Business methods ( Transfer business )
- Who is the notice ? Transaction control function
- Configuration aspect ?
be based on xml Implementation of declarative transaction control
The target audience is service Objects in layers , The internal method is the tangent point .
Realization of transfer business
dao Layer code :
public interface AccountDao {
public void out(String outMan,double money);
public void in(String inMan,double money);
}
public class AccountDaoImpl implements AccountDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void out(String outMan, double money) {
jdbcTemplate.update("update account set money=money-? where name=?",money,outMan);
}
public void in(String inMan, double money) {
jdbcTemplate.update("update account set money=money+? where name=?",money,inMan);
}
}
Business layer code :
public interface AccountService {
public void transfer(String outMan, String inMan, double money);
}
public class AccountServiceImpl implements AccountService {
private AccountDao accountDao;
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
public void transfer(String outMan, String inMan, double money) {
accountDao.out(outMan,money);
int i=1/0;
accountDao.in(inMan,money);
}
}
web Layer code :
public class AccountController {
public static void main(String[] args) {
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
AccountService accountService = app.getBean(AccountService.class);
accountService.transfer("lucy","tom",500);
}
}
Spring Of xml File configuration :
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="124869"/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="accountDao" class="com.dao.impl.AccountDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>
<!-- Target audience The internal method is the tangent point -->
<bean id="accountService" class="com.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"/>
</bean>
① introduce tx Namespace
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

② Configure transaction enhancements
<!-- Configure platform transaction manager , stay jdbcTemplate and mybatis Are used in DataSourceTransactionManager -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- notice Enhanced configuration of transactions , You also need to specify the platform transaction manager ( Which item is used Dao Layer technology )-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!--tx:attributes, Refers to the attribute information of the transaction ,tx:method It means which methods are enhanced , There are many other properties that follow -->
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
③ Configure transactions AOP Weaving
<!-- The transaction aop enhance -->
<aop:config>
<!--spring Specifically for transaction enhancement advisor To configure , This is also cut , It is a facet of notification , Common enhanced use aspect-->
<aop:pointcut id="myPointcut" expression="execution(* com.itheima.service.impl.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="myPointcut"></aop:advisor>
</aop:config>
④ Test transaction control transfer business code
@Override
public void transfer(String outMan, String inMan, double money) {
accountDao.out(outMan,money);
int i = 1/0;
accountDao.in(inMan,money);
}
Configuration of transaction parameters of pointcut method
<!-- Transaction enhancement configuration -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--tx:attributes, Refers to the attribute information of the transaction ,tx:method It means which methods are enhanced , There are many other properties that follow -->
<tx:attributes>
<!-- You can configure different properties for different methods -->
<tx:method name="*"/>
<tx:method name="transfer" isolation="REPEATABLE_READ" propagation="REQUIRED" timeout="-1" read-only="false"/>
<tx:method name="findAll" isolation="REPEATABLE_READ" propagation="REQUIRED" timeout="-1" read-only="true"/>
<!-- With update Opening method -->
<tx:method name="update*" isolation="REPEATABLE_READ" propagation="REQUIRED" timeout="-1" read-only="false"/>
</tx:attributes>
</tx:advice>
among ,<tx:method> Represents the configuration of the transaction parameters of the pointcut method , for example :<tx:method name="transfer" isolation="REPEATABLE_READ" propagation="REQUIRED" timeout="-1" read-only="false"/>
- name: Pointcut method name
- isolation: The isolation level of the transaction
- propogation: The spread of transactions
- timeout: Timeout time
- read-only: Is it read-only
Knowledge points
Configuration points of declarative transaction control
- Platform transaction manager configuration
- Configuration of transaction notification
- Business aop Weaving configuration
Declarative transaction control based on annotations
Use annotations to configure declarative transaction control
1. To write AccoutDao
@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public void out(String outMan, double money) {
jdbcTemplate.update("update account set money=money-? where name=?",money,outMan);
}
public void in(String inMan, double money) {
jdbcTemplate.update("update account set money=money+? where name=?",money,inMan);
}
}
2. To write AccoutService
@Service("accountService")
@Transactional
// All methods under this class are represented by this transaction attribute parameter ,
// The principle of proximity , If this annotation also exists on the method , This method uses the attributes of the method itself
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED)
public void transfer(String outMan, String inMan, double money) {
accountDao.out(outMan,money);
int i = 1/0;
accountDao.in(inMan,money);
}
}
3. To write applicationContext.xml The configuration file
<!— Omit... Before datsSource、jdbcTemplate、 Configuration of platform transaction manager -->
<!-- Component scan -->
<context:component-scan base-package="com"/>
<!-- Annotation driven transactions -->
<tx:annotation-driven/>
Annotation configuration declarative transaction control resolution
① Use @Transactional Modify the class or method that needs transaction control , The properties available for annotations are the same as xml Configuration mode , For example, isolation level 、 Communication behavior, etc .
② Annotations are used on classes , All methods in this class are configured with the same set of annotation parameters .
③ Use it in a way , Different methods can adopt different transaction parameter configuration .
④ Xml In the configuration file, you need to turn on the annotation driver of the transaction <tx:annotation-driven />
Knowledge points
Annotate the configuration points of declarative transaction control
- Platform transaction manager configuration (xml The way )
- Configuration of transaction notification (@Transactional Annotation configuration )
- Transaction annotation driven configuration
<tx:annotation-driven/>
边栏推荐
- How to drain the applet correctly? Three positions of whole network drainage!
- How to gracefully realize regular backup of MySQL database (glory Collection Edition)
- [Matplotlib drawing]
- [crawler knowledge] better than lxml and BS4? Use of parser
- P2404 splitting of natural numbers
- Sqlserver BCP parameter interpretation, character format selection and fault handling summary
- Build Tencent cloud website server at low cost (build your own website server)
- Drawing library Matplotlib drawing
- 【二分好题】
- 01_ UE4 advanced_ PBR material
猜你喜欢

Conditional judgment of Shell Foundation

MySQL - multi table query - seven join implementations, set operations, multi table query exercises

Leetcode skimming -- bit by bit record 017

Feeding Program Source Code to ZK VMs

Nested printing in CAD web pages

Understand MySQL index and b+tree in an easy to understand way (supreme Collection Edition)
[email protected]"/>@typescript-eslint/ [email protected]

Gather relevant knowledge points and expand supplements

Redefine analysis - release of eventbridge real-time event analysis platform

Documentary of the second senior brother
随机推荐
Scientific computing toolkit SciPy data interpolation
LED digital display driver IC and anti-interference LED digital tube display driver ic-vk1s68c ssop24 are applicable to finger clip pulse oximeter, arm electronic sphygmomanometer, thermometer, fetal
Can bank financial products be redeemed and transferred out on the same day?
Using skills and design scheme of redis cache (classic collection version)
@typescript-eslint/ [email protected]
Volcano engine releases cloud growth solutions for six industries
[jzof] 04 search in two-dimensional array
01_ UE4 advanced_ PBR material
It's the same type of question as just K above
MySQL - multi table query - seven join implementations, set operations, multi table query exercises
Among the database accounts in DTS, the accounts of MySQL database and mongodb database appear most. What are the specific accounts
[SOC] the first project of SOC Hello World
How does redis realize inventory deduction and prevent oversold? (glory Collection Edition)
Redis (12) -- redis server
Which type of database migration is suitable for choosing the self built database access method on ECs?
Circom 2.0: A Scalable Circuit Compiler
Mysql database commands
微机原理:CPU架构详解
CAD disable a button on the toolbar (WEB version)
陈春花与莫言,都有苦难言