【Spring】Spring複習第五天

Spring中的事務控制

1. Spring事務控制我們要明確的

第一:JavaEE體系進行分層開發,事務處理位於業務層,Spring 提供了分層設計業務層的事務處理解決方案。

第二:Spring 框架爲我們提供了一組事務控制的接口。在spring-tx-4.2.3.RELEASE.jar 中。

第三:Spring 的事務控制都是基於AOP的,它既可以使用編程的方式實現,也可以使用配置的方式實現。

2. Spring事務控制的API介紹

2.1 PlatformTransactionManager

此接口是Spring的事務管理器,裏面提供了很多我們常用的操作事務的方法。
在這裏插入圖片描述
我們用的都是他的實現類,真正管理事務的對象:

  • org.springframework.jdbc.datasource.DataSourceTransactionManager 使用 Spring
    JDBC 或 Mybatis 進行持久化數據時使用
  • org.springframework.orm.hibernate5.HibernateTransactionManager 使用
    Hibernate 版本進行持久化數據時使用

2.2 TransactionDefinition
在這裏插入圖片描述
2.3 事務的隔離級別
在這裏插入圖片描述
2.3 事務的傳播行爲

  • REQUIRED:如果沒有當前事務,就新建一個事務,如果已經存在一個事務中,就加入到這個事務中。一般的選擇(默認值)。
  • SUPPORTS:支持當前事務,如果當前沒有事務,就以非事務的方式執行(沒有事務)。
  • MANDATORY:使用當前的事務,如果當前沒有事務,就拋出異常
  • REQUERS_NEW:新建事務,如果當前在事務中,把當前事務掛起。
  • NOT_SUPPORTED:以非事務方式執行操作,如果當前存在事務,就把當前事務掛起
  • NEVER:以非事務方式運行,如果當前存在事務,拋出異常
  • NESTED:如果當前存在事務,則在嵌套事務內執行。如果當前沒有事務,則執行 REQUIRED 類似的操作

2.4 超時時間

默認值是-1,沒有超時限制,如果有,以秒爲單位進行設置。

2.5 是否是隻讀事務

建議查詢時設置爲只讀。

3. TransactionStatus

此接口提供的是事務具體的運行狀態,方法介紹如下圖:
在這裏插入圖片描述
4. 基於XML的聲明式事務控制(配置方式)

4.1 環境搭建

(1)導入需要的jar包。
在這裏插入圖片描述
(2)創建Spring的配置文件並導入約束

此處需要導入aop和tx兩個名稱空間。

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

</beans>

(3)準備數據庫表和實體類

創建數據庫:
create database mydb;
use mydb;
創建表:
create table account(
id int primary key auto_increment,
name varchar(40),
money float
)character set utf8 collate utf8_general_ci;
/**
 * 賬戶的實體類
 */
public class Account implements Serializable {
    private Integer id;
    private String name;
    private Float money;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Float getMoney() {
        return money;
    }

    public void setMoney(Float money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

(4)編寫業務層接口和實體類

/**
 * 賬戶的業務層接口
 */
public interface IAccountService {

    /**
     * 根據賬戶名稱查詢賬戶信息
     * @param accountId
     * @return
     */
    Account findAccountById(Integer accountId);

    /**
     * 轉賬
     * @param sourceName:轉出賬戶名稱
     * @param targetName:張如賬戶名稱
     * @param money:轉賬金額
     */
    public void transfer(String sourceName,String targetName,Float money);

}

/**
 * 賬戶的業務層實現類
 */
public class AccountServiceImpl implements IAccountService {

    private IAccountDao accountDao;

    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);
    }

    @Override
    public void transfer(String sourceName, String targetName, Float money) {
        //1.根據名稱查詢賬戶
        Account source = accountDao.findAccountByName(sourceName);
        Account target = accountDao.findAccountByName(targetName);
        //2.轉出賬戶減錢,轉入賬戶加錢
        source.setMoney(source.getMoney() - money);
        target.setMoney(target.getMoney() + money);
        //3.更新賬戶信息
        accountDao.updateAccount(source);
        int i = 1/0;
        accountDao.updateAccount(target);
    }
}

(5)編寫Dao接口和實體類

/**
 * 賬戶的接口
 */
public interface IAccountDao {
    /**
     * 根據id查詢賬戶信息
     */
    public Account findAccountById(Integer id);

    /**
     * 根據名稱查詢賬戶信息
     */
    public Account findAccountByName(String name);

    /**
     * 更新賬戶信息
     */
    public void updateAccount(Account account);
}
/**
 * 賬戶的業務層實現類
 */
public class AccountServiceImpl implements IAccountService {

    private IAccountDao accountDao;

    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);
    }

    @Override
    public void transfer(String sourceName, String targetName, Float money) {
        //1.根據名稱查詢賬戶
        Account source = accountDao.findAccountByName(sourceName);
        Account target = accountDao.findAccountByName(targetName);
        //2.轉出賬戶減錢,轉入賬戶加錢
        source.setMoney(source.getMoney() - money);
        target.setMoney(target.getMoney() + money);
        //3.更新賬戶信息
        accountDao.updateAccount(source);
        int i = 1/0;
        accountDao.updateAccount(target);
    }
}

(6)在配置文件中配置業務層和持久層

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

    <!--配置service-->
    <bean id="accountService" class="com.renjing.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>
    <!--配置dao-->
    <bean id="accountDao" class="com.renjing.dao.impl.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"></property><!--配置關聯的數據源-->
    </bean>
    <!--配置Spring內置數據源-->
   <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
       <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
       <property name="url" value="jdbc:mysql://localhost:3306/mydb"/>
       <property name="username" value="root"/>
       <property name="password" value="root"/>
   </bean>
</beans>

5. 配置步驟

5.1 第一步:配置事務管理器

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入數據源-->
        <property name="dataSource" ref="dataSource"></property>
</bean>

5.2 第二步:配置事務的通知引用事務管理器

<tx:advice id="txAdvice" transaction-manager="transactionManager">
</tx:advice>

5.3 第三步:配置事務的屬性

<tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
        <!--指定方法名稱:是業務核心方法
        	read-only:是否是隻讀事務。默認false,不只讀。
        	isolation:指定事務的隔離級別。默認值是使用數據庫的默認隔離級別。mysql爲REPEATABLE-READ
        	propagation:指定事務的傳播行爲。
        	timeout:指定超時時間。默認值爲-1.永不超時。
        	rollback-for:用於指定一個異常,當執行產生該異常時,事務回滾。產生其他異常,事務不回滾。沒有默認值,任何異常都回滾。
        	no-rollback-for:用於指定一個異常,當產生該異常時,事務不回滾,產生其他異常時,事務回滾。沒有默認值,任何異常都會滾。-->
            <tx:method name="*" propagation="REQUIRED"/>
            <tx:method name="find*" propagation="SUPPORTS"/>
        </tx:attributes>
    </tx:advice>

5.4 配置AOP切入點表達式

<aop:config>
        <!--切入點表達式-->
        <aop:pointcut id="pt1" expression="execution(* com.renjing.service.impl.*.*(..))"></aop:pointcut>
</aop:config>

5.5 配置切入點表達式和事務通知的對應關係

<aop:config>
        <!--切入點表達式-->
        <aop:pointcut id="pt1" expression="execution(* com.renjing.service.impl.*.*(..))"></aop:pointcut>
        <!--建立事務的通知和切入點表達式之間的關係-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
</aop:config>

5.6 XML配置文件如下

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

    <!--配置service-->
    <bean id="accountService" class="com.renjing.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>
    <!--配置dao-->
    <bean id="accountDao" class="com.renjing.dao.impl.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"></property><!--配置關聯的數據源-->
    </bean>
    <!--配置Spring內置數據源-->
   <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
       <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
       <property name="url" value="jdbc:mysql://localhost:3306/mydb"/>
       <property name="username" value="root"/>
       <property name="password" value="root"/>
   </bean>

    <!--Spring基於XML的聲明式事務控制-->
    <!--第一步:配置事務管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入數據源-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--第二步:配置事務的通知引用事務管理器-->
    <!--事務的配置-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED"/>
            <tx:method name="find*" propagation="SUPPORTS"/>
        </tx:attributes>
    </tx:advice>
    <!--第三步:配置aop:切入點表達式,通知和切入點表達式的關聯-->
    <aop:config>
        <!--切入點表達式-->
        <aop:pointcut id="pt1" expression="execution(* com.renjing.service.impl.*.*(..))"></aop:pointcut>
        <!--建立事務的通知和切入點表達式之間的關係-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
    </aop:config>
</beans>

6. 基於註解的配置方式

(1)使用上面的代碼進行修改即可,故配置的環境相同。此處不再贅述。

(2)將業務層接口和實現類交給Spring管理。

/**
 * 業務層的實現類
 */
@Service("accountService")
public class AccountServiceImpl implements IAccountService {

    @Autowired
    private IAccountDao accountDao;

    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    @Transactional(readOnly = true,propagation = Propagation.SUPPORTS)//只讀型
    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);
    }

    @Override
    public void transfer(String sourceName, String targetName, Float money) {
        //1.根據名稱查詢賬戶
        Account source = accountDao.findAccountByName(sourceName);
        Account target = accountDao.findAccountByName(targetName);
        //2.轉出賬戶減錢,轉入賬戶加錢
        source.setMoney(source.getMoney() - money);
        target.setMoney(target.getMoney() + money);
        //3.更新賬戶信息
        accountDao.updateAccount(source);
        int i = 1/0;
        accountDao.updateAccount(target);
    }
}

(3)將Dao層接口和實現類交給Spring管理。

/**
 * 賬戶的持久層實現類
 * 需要給dao注入JdbcTemplate
 */
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public Account findAccountById(Integer id) {
        List<Account> accounts = jdbcTemplate.query("select * from account where id = ?", new BeanPropertyRowMapper<Account>(Account.class), id);
        return accounts.isEmpty()?null:accounts.get(0);
    }

    @Override
    public Account findAccountByName(String name) {
        List<Account> accounts = jdbcTemplate.query("select * from account where name = ?", new BeanPropertyRowMapper<Account>(Account.class), name);
        if (accounts.isEmpty()) {//此處不需要判斷list是否爲null,因爲在封裝數據的時候,肯定已經有一個list了
            return null;
        }
        if (accounts.size() > 1) {
            throw new RuntimeException("結果集不唯一,請檢查數據");
        }
        return accounts.get(0);
    }

    @Override
    public void updateAccount(Account account) {
        jdbcTemplate.update("update account set money = ? where id = ?",account.getMoney(),account.getId());
    }
}

(4)配置步驟

①開啓創建Spring容器時要掃描的包。

<context:component-scan base-package="com.renjing"></context:component-scan>

②配置jdbcTemplate。

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <!--必須要注入數據源-->
        <property name="dataSource" ref="dataSource"></property>
</bean>

③配置Spring內置數據源。

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

④配置事務管理器並注入數據源。

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入數據源-->
        <property name="dataSource" ref="dataSource"></property>
</bean>

⑤開啓Spring對註解事務的支持。

<tx:annotation-driven transaction-manager="transactionManager"/>

⑥在業務層使用@Transactional註解。
(在需要事務的地方使用@Transactional註解)

/**
 * 業務層的實現類
 */
@Service("accountService")
@Transactional(readOnly = false,propagation = Propagation.REQUIRED)//讀寫型事務
public class AccountServiceImpl implements IAccountService {

    /**
     * @Transactional註解:該註解的屬性和xml中的屬性含義一致.該註解可以出現在接口上,類上,方法上.
     * 出現在接口上,表示該接口的所有方法都有事務支持.
     * 出現在類上,表示類中所有方法有事務支持.
     * 出現在方法上,表示方法有事務支持.
     * 以上三個位置優先級:方法>類>接口
     */
    @Autowired
    private IAccountDao accountDao;

    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    @Transactional(readOnly = true,propagation = Propagation.SUPPORTS)//只讀型
    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);
    }

    @Override
    public void transfer(String sourceName, String targetName, Float money) {
        //1.根據名稱查詢賬戶
        Account source = accountDao.findAccountByName(sourceName);
        Account target = accountDao.findAccountByName(targetName);
        //2.轉出賬戶減錢,轉入賬戶加錢
        source.setMoney(source.getMoney() - money);
        target.setMoney(target.getMoney() + money);
        //3.更新賬戶信息
        accountDao.updateAccount(source);
        int i = 1/0;
        accountDao.updateAccount(target);
    }
}

  1. 純註解配置方式
/**
 * 鏈接數據庫的配置類
 */
public class JdbcConfig {

    @Bean(name = "jdbcTemplate")
    public JdbcTemplate createJdbcTemplate(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    @Bean(name = "dataSource")
    public DataSource createDataSource(){
        DriverManagerDataSource ds = new DriverManagerDataSource();
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        ds.setUrl("jdbc:mysql://localhost:3306/mydb");
        ds.setUsername("root");
        ds.setPassword("root");
        return ds;
    }
}
/**
 * 事務控制的配置類
 */
public class TransactionManager {

    @Bean(name = "transactionManager")
    public PlatformTransactionManager createTransactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
/**
 * Spring的配置類
 */
@Configuration
@ComponentScan("com.renjing")
@Import({JdbcConfig.class, TransactionManager.class})
@EnableTransactionManagement//開啓Spring對註解aop的支持
public class SpringConfiguration {

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章