Understanding of Spring transaction control

Configure JdbcTemplate in the spring configuration file

<!-- 配置一个数据库的操作模板:JdbcTemplate --> 

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property>
</bean>

<!-- 配置数据源 -->

 <bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
 <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> 
<property name="url" value="jdbc:mysql:///spring_day02"></property>
 <property name="username" value="root"></property>
 <property name="password" value="root"></property>
</bean>
</beans>

Use JdbcTemplate in dao

The first way to define the JdbcTemplate in the Dao class is applicable to all configuration methods (xml and annotations are fine).
The second way for Dao to inherit JdbcDaoSupport can only be used in an XML-based way, and annotations are not used.

The first way: define JdbcTemplate in dao

//上面已配置template
<bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
<!-- 注入 jdbcTemplate --> <property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>

The second way: let dao inherit JdbcDaoSupport
JdbcDaoSupport is a class provided by spring framework for us, this class defines a JdbcTemplate object, there is a serDataSourece method inside, we can get it directly, but to create this object, we need to It provides a data source:

<bean id="accountDao2" class="com.itheima.dao.impl.AccountDaoImpl2">
<!-- 注入 dataSource -->
 <property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置数据源 --> 
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql:///spring_day04"></property> <property name="username" value="root"></property> <property name="password" value="1234"></property>
</

Then use getJdbcTemplate () directly in the class

Introduction to API for transaction control in Spring

spring xml constraint

Prepare package import for spring-tx and aspectjweaver

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="
http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans.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/context 
 http://www.springframework.org/schema/context/spring-context.xsd">

PlatformTransactionManager
This interface is spring's transaction manager, which provides our commonly used methods of operating transactions

Objects that really manage transactions
org.springframework.jdbc.datasource.DataSourceTransactionManager use Spring JDBC or MyBatis for persistent data

TransactionDefinition
is a transaction definition information object, which has the following methods:

Get the name of the transaction object
A String getName ()
Get the transaction isolation level
A int getlsolationLevel ()
Get the transaction propagation behavior
A int getPropagationBehavior ()
Get the transaction timeout time
A intgetTimeout ()
Get whether the transaction is read-only
A boolean isReadOnly ()

Transactional behavior

REQUIRED: If there is currently no transaction, create a new transaction, if there is already a transaction, add to this transaction. General selection (default value)
SUPPORTS: support current transaction, if there is no transaction, it will be executed in a non-transactional way (no transaction)
MANDATORY: use the current transaction, if there is no transaction, then throw an exception
REQUERS_NEW: new transaction Currently in the transaction, suspend the current transaction.
NOT_SUPPORTED: Perform operations in non-transactional mode, if there is currently a transaction, suspend the current transaction
NEVER: Run in non-transactional mode, if there is currently a transaction, throw an exception
NESTED: If there is currently a transaction, execute it in a nested transaction . If there is currently no transaction, perform a similar operation REQUIRED.

The timeout
value is -1 by default, and there is no timeout limit. If there is, set it in seconds.

Whether it is a read-only transaction It is
recommended to set to read-only during query.
`
TransactionStatus
This interface provides the specific running status of the transaction, method introduction:

The Transactionstatus interface describes the status information of transaction objects at a certain point in time, and contains 6 specific operations


-Refresh the transaction- void flush ()-Get
whether there is a storage point
-boolean hasSavepoint ()-Get the
transaction completed-
boolean isCompleted ()-Get the
transaction is a new transaction
-boolean isNewTransaction ()-Get the
transaction rollback setting Transaction rollback—
boolean isRollbackOnly () void setRollbackOnly ()

Configuration steps in XML

1. Configure the transaction manager

<!-- 配置一个事务管理器 -->
 <bean id="transactionManager"  class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入 DataSource -->  
<property name="dataSource" ref="dataSource"></property>
</bean>

2. Notification of configuration transaction refers to transaction manager

<!-- 事务的配置 --> 
<tx:advice id="txAdvice" transaction-manager="transactionManager"> </tx:advice>

3. Configure the properties of the transaction

<!-- 指定方法名称:是业务核心方法
read-only:是否是只读事务。默认 false,不只读。
isolation:指定事务的隔离级别。默认值是使用数据库的默认隔离级别。
propagation:指定事务的传播行为。默认值是require 。查询方法时可用support
timeout:指定超时时间。默认值为:-1。永不超时。
rollback-for:用于指定一个异常,当执行产生该异常时,事务回滚。产生其他异常,事务不回滚。
没有默认值,任何异常都回滚。
no-rollback-for:用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时,事务回
滚。没有默认值,任何异常都回滚。-->

 <!--在 tx:advice 标签内部 配置事务的属性 -->
 <tx:attributes>
 <tx:method name="*" read-only="false" propagation="REQUIRED"/>
<tx:method name="find*" read-only="true" propagation="SUPPORTS"/>
</tx:attributes>

4. Configure AOP pointcut expression

<!-- 配置 aop -->
 <aop:config>
<!-- 配置切入点表达式 --> 
<aop:pointcut  id="pt1"  expression="execution(* com.itheima.service.impl.*.*(..))"  />
</aop:config>

5. Configure the correspondence between pointcut expressions and transaction notifications

<!-- 在 aop:config 标签内部:建立事务的通知和切入点表达式的关系 -->
 <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>

Annotation configuration

Step 1: Configure the transaction manager and inject the data source

<!-- 配置事务管理器 --> 
<bean id="transactionManager"  class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 
<property name="dataSource" ref="dataSource"></property>
</bean>

Or do not use xml configuration, you can omit the third step

@Configuration
@EnableTransactionManagement
public class SpringTxConfiguration {
// Configure the data source, JdbcTemplate, and transaction manager in the class.
}

Step 2: Use @Transactional annotation in the business layer
. The attribute of this annotation has the same meaning as the attribute in xml. This annotation can appear on interfaces, classes, and methods.
Appears on the interface, indicating that all implementation classes of the interface have transaction support.
Appears on the class, indicating that all methods in the class have transaction support
Appears on the method, indicating that the method has transaction support.
Priority of the above three positions: method> class> interface

@Service("accountService")

@Transactional(readOnly=true,propagation=Propagation.SUPPORTS)

public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao;
@Override
public Account findAccountById(Integer id) {
return accountDao.findAccountById(id);
}
@Override

@Transactional(readOnly=false,propagation=Propagation.REQUIRED)

public void transfer(String sourceName, String targeName, Float money) {
//1.根据名称查询两个账户
Account source = accountDao.findAccountByName(sourceName);
Account target = accountDao.findAccountByName(targeName);
//2.修改两个账户的金额
source.setMoney(source.getMoney()-money);//转出账户减钱
target.setMoney(target.getMoney()+money);//转入账户加钱
//3.更新两个账户
accountDao.updateAccount(source);
//int i=1/0;
accountDao.updateAccount(target);
} }

The third step: open spring support for annotation transactions in the configuration file

<!-- 开启 spring 对注解事务的支持 --> 
<tx:annotation-driven transaction-manager="transactionManager"/>
Published 43 original articles · praised 2 · visits 991

Guess you like

Origin blog.csdn.net/study_azhuo/article/details/105532975