当前位置:网站首页>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/>
边栏推荐
- What are the most problematic database accounts in DTS?
- Redis (12) -- redis server
- String matching (Huawei)
- Easily make 2D tile map with unity tilemap - Basics
- ESP32C3 LED PWM使用和ESP32差异说明
- 图像处理笔记(1)图像增强
- [Development Tutorial 4] open source Bluetooth heart rate waterproof sports Bracelet - external flash reading and writing
- 2022 Tsinghua summer school notes L2_ 2 basic introduction of CNN and RNN
- OSI architecture and protocols at all levels
- 模板的使用
猜你喜欢

Codeforces Round #809 (Div. 2)(A~D2)

Mysql database query is so slow. Besides index, what else can it do?

The relationship between cloud computing and digital transformation has finally been clarified

2022 Tsinghua summer school notes L2_ 2 basic introduction of CNN and RNN

Image processing notes (1) image enhancement

How to design the order system in e-commerce projects? (supreme Collection Edition)

91. (leaflet chapter) leaflet situation plotting - offensive direction drawing
![[image processing] pyefd.elliptic_ fourier_ How descriptors are used](/img/72/d2c825ddd95f541b37b98b2d7f6539.png)
[image processing] pyefd.elliptic_ fourier_ How descriptors are used

String matching (Huawei)

Little Red Book Keyword Search commodity list API interface (commodity detail page API interface)
随机推荐
运动控制如何位置同步输出
String matching (Huawei)
[Matplotlib drawing]
Alibaba cloud and parallel cloud launched the cloud XR platform to support the rapid landing of immersive experience applications
How does redis realize inventory deduction and prevent oversold? (glory Collection Edition)
Brand new: the latest ranking of programming languages in July
How to gracefully realize regular backup of MySQL database (glory Collection Edition)
[jzof] 05 replace spaces
[combination of classes (define a class in a class)]
IO flow overview
OSI architecture and protocols at all levels
一种自动化九点标定工具原理(包涵部分源码)
Multiplication and addition of univariate polynomials
MySQL forced indexing
"Iruntime": undeclared identifier
About the acid of MySQL, there are thirty rounds of skirmishes with mvcc and interviewers
Discussion on solving the application ecological problems of domestic systems based on small programs
ESP32C3 LED PWM使用和ESP32差异说明
“IRuntime”: 未声明的标识符
Makefile basics -- extensions