当前位置:网站首页>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 about opening an account for CITIC Securities? Is it safe
- 模板的使用
- 如何修改 Kubernetes 节点 IP 地址?
- Practical skills!!
- Drawing library Matplotlib styles and styles
- Scientific computing toolkit SciPy Fourier transform
- Penetration test - command execution injection
- [crawler knowledge] better than lxml and BS4? Use of parser
- Establishment of China Mobile Chain (EOS based) test environment
- Get data in batches according to time
猜你喜欢
![[combination of classes (define a class in a class)]](/img/ae/a8226e1795bb45171a11c65d35bcac.png)
[combination of classes (define a class in a class)]
![[Matplotlib drawing]](/img/ac/dea6fa0aff6f02477fba48c929fadc.png)
[Matplotlib drawing]

Understand MySQL index and b+tree in an easy to understand way (supreme Collection Edition)

Information System Project Manager - Chapter 10 project communication management and project stakeholder management

01_ UE4 advanced_ PBR material

ERROR 2003 (HY000): Can‘t connect to MySQL server on ‘localhost:3306‘ (10061)

小程序地理位置接口申请

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

Conditional judgment of Shell Foundation
![[jzof] 05 replace spaces](/img/af/62432e0d6310d575a54e9409da0c32.png)
[jzof] 05 replace spaces
随机推荐
[SOC] the first project of SOC Hello World
Mysql database query is so slow. Besides index, what else can it do?
[good question with two points]
Is it safe to open an account on Alipay
【Pyspark基础】行转列和列转行(超多列时)
What should I do to select the method of mongodb instance accessing the database?
[jzof] 05 replace spaces
Can bank financial products be redeemed and transferred out on the same day?
Little Red Book Keyword Search commodity list API interface (commodity detail page API interface)
Nested printing in CAD web pages
Using gcc to avoid stack smash attack
How to realize three schemes of finclip wechat authorized login
Mysql database commands
Day5: three pointers describe a tree
P2404 splitting of natural numbers
运动控制如何位置同步输出
How to gracefully realize regular backup of MySQL database (glory Collection Edition)
@typescript-eslint/ [email protected]
《论文复现》BiDAF代码实现过程(4)模型训练+验证
如何修改 Kubernetes 节点 IP 地址?