spring04JdbcTemplate和事務(wù)

JdbcTemplate基本使用

01-JdbcTemplate基本使用-概述(了解)

JdbcTemplate是spring框架中提供的一個對象,是對原始繁瑣的Jdbc API對象的簡單封裝。spring框架為我們提供了很多的操作模板類。例如:操作關(guān)系型數(shù)據(jù)的JdbcTemplate和HibernateTemplate,操作nosql數(shù)據(jù)庫的RedisTemplate,操作消息隊列的JmsTemplate等等。

02-JdbcTemplate基本使用-開發(fā)步驟(理解)

①導(dǎo)入spring-jdbc和spring-tx坐標

②創(chuàng)建數(shù)據(jù)庫表和實體

③創(chuàng)建JdbcTemplate對象

④執(zhí)行數(shù)據(jù)庫操作

03-JdbcTemplate基本使用-快速入門代碼實現(xiàn)(應(yīng)用)

導(dǎo)入spring-jdbc和spring-tx坐標

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.itheima</groupId>
  <artifactId>itheima_spring_jdbc</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>itheima_spring_jdbc Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>
  <dependencies>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.32</version>
    </dependency>
    <dependency>
      <groupId>c3p0</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.1.2</version>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.10</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.0.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>5.0.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>5.0.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.0.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.0.1</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.2.1</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.9.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.9.0</version>
    </dependency>
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.3</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.0.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>5.0.5.RELEASE</version>
    </dependency>
  </dependencies>
</project>

創(chuàng)建數(shù)據(jù)庫表和實體

package com.nono.domain;

public class Account {

    private String name;
    private Double money;

    public String getName() {
        return name;
    }

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

    public Double getMoney() {
        return money;
    }

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

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

創(chuàng)建JdbcTemplate對象

執(zhí)行數(shù)據(jù)庫操作

package com.nono.test;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.Test;
import org.springframework.jdbc.core.JdbcTemplate;

import java.beans.PropertyVetoException;

public class JdbcTemplateTest {

    @Test
    public void test1() throws PropertyVetoException {
        //創(chuàng)建數(shù)據(jù)源對象
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass("com.mysql.jdbc.Driver");
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/nono");
        dataSource.setUser("root");
        dataSource.setPassword("123456");

        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        //設(shè)置數(shù)據(jù)源對象  知道數(shù)據(jù)庫在哪
        jdbcTemplate.setDataSource(dataSource);
        int row = jdbcTemplate.update("insert into account value (?,?)", "tom", 5000);
        System.out.println(row);

    }
}

04-JdbcTemplate基本使用-spring產(chǎn)生模板對象分析(理解)

我們可以將JdbcTemplate的創(chuàng)建權(quán)交給Spring,將數(shù)據(jù)源DataSource的創(chuàng)建權(quán)也交給Spring,在Spring容器內(nèi)部將數(shù)據(jù)源DataSource注入到JdbcTemplate模版對象中,然后通過Spring容器獲得JdbcTemplate對象來執(zhí)行操作。

05-JdbcTemplate基本使用-spring產(chǎn)生模板對象代碼實現(xiàn)(應(yīng)用)

配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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">
    <!--數(shù)據(jù)源對象-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/nono"></property>
        <property name="user" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>
    <!--jdbc模板對象-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
</beans>

測試代碼

 @Test
   //測試Spring產(chǎn)生jdbcTemplate對象
    @Test
    public void test2() throws PropertyVetoException {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        JdbcTemplate jdbcTemplate = applicationContext.getBean(JdbcTemplate.class);
        int row = jdbcTemplate.update("insert into account value (?,?)", "Jerry", 6000);
        System.out.println(row);

    }

06-JdbcTemplate基本使用-spring產(chǎn)生模板對象代碼實現(xiàn)(抽取jdbc.properties)(應(yīng)用)

將數(shù)據(jù)庫的連接信息抽取到外部配置文件中,和spring的配置文件分離開,有利于后期維護

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/nono
jdbc.username=root
jdbc.password=123456

配置文件修改為:

<?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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">

    <!--加載jdbc.properties-->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
    <!--數(shù)據(jù)源對象-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
    <!--jdbc模板對象-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
</beans>

07-JdbcTemplate基本使用-常用操作-更新操作(應(yīng)用)

package com.nono.test;


import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class JdbcTemplateCRUDTest {

    @Autowired
    private JdbcTemplate jdbcTemplate;


    //插入
    @Test
    public void testInsert() {
        int row = jdbcTemplate.update("insert into account value (?,?)", "Jerry", 6000);
        System.out.println(row);
    }
    //修改更新
    @Test
    public void testUpdata(){
        int row = jdbcTemplate.update("update account set money = ? where name = ?", 7500, "Tom");
        System.out.println(row);
    }

    //刪除
    @Test
    public void testDelete(){
        int row = jdbcTemplate.update("delete from account where name = ?","Jerry");
        System.out.println(row);
    }


    
}

08-JdbcTemplate基本使用-常用操作-查詢操作(應(yīng)用)

package com.itheima.test;

import com.itheima.domain.Account;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class JdbcTemplateCRUDTest {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    
     //聚合查詢
    @Test
    public void testQueryCount() {
        Long count = jdbcTemplate.queryForObject("select count(*) from account", Long.class);
        System.out.println(count);
    }

    //查詢單個
    @Test
    public void testQueryOne() {
        Account account = jdbcTemplate.queryForObject("select * from account where name = ?", new BeanPropertyRowMapper<Account>(Account.class), "Tom");
        System.out.println(account);
    }


    //查詢所有
    @Test
    public void testQueryAll() {
        List<Account> list = jdbcTemplate.query("select * from account", new BeanPropertyRowMapper<Account>(Account.class));
        System.out.println(list);
    }
}

09-JdbcTemplate基本使用-知識要點(理解,記憶)

①導(dǎo)入spring-jdbc和spring-tx坐標

②創(chuàng)建數(shù)據(jù)庫表和實體

③創(chuàng)建JdbcTemplate對象

        JdbcTemplate jdbcTemplate = newJdbcTemplate();
           jdbcTemplate.setDataSource(dataSource);

④執(zhí)行數(shù)據(jù)庫操作

更新操作:

    jdbcTemplate.update (sql,params)

查詢操作:

    jdbcTemplate.query (sql,Mapper,params)

jdbcTemplate.queryForObject(sql,Mapper,params)

聲明式事務(wù)控制

1. 編程式事務(wù)控制相關(guān)對象

1.1 PlatformTransactionManager

PlatformTransactionManager 接口是 spring 的事務(wù)管理器,它里面提供了我們常用的操作事務(wù)的方法。

2.png

注意:

PlatformTransactionManager 是接口類型,不同的 Dao 層技術(shù)則有不同的實現(xiàn)類,例如:Dao 層技術(shù)是jdbc 或 mybatis 時:org.springframework.jdbc.datasource.DataSourceTransactionManager

Dao 層技術(shù)是hibernate時:org.springframework.orm.hibernate5.HibernateTransactionManager

1.2 TransactionDefinition

TransactionDefinition 是事務(wù)的定義信息對象,里面有如下方法:

3.png

1. 事務(wù)隔離級別

設(shè)置隔離級別,可以解決事務(wù)并發(fā)產(chǎn)生的問題,如臟讀、不可重復(fù)讀和虛讀。

  • ISOLATION_DEFAULT

  • ISOLATION_READ_UNCOMMITTED

  • ISOLATION_READ_COMMITTED

  • ISOLATION_REPEATABLE_READ

  • ISOLATION_SERIALIZABLE

2. 事務(wù)傳播行為

  • REQUIRED:如果當前沒有事務(wù),就新建一個事務(wù),如果已經(jīng)存在一個事務(wù)中,加入到這個事務(wù)中。一般的選擇(默認值)

  • SUPPORTS:支持當前事務(wù),如果當前沒有事務(wù),就以非事務(wù)方式執(zhí)行(沒有事務(wù))

  • MANDATORY:使用當前的事務(wù),如果當前沒有事務(wù),就拋出異常

  • REQUERS_NEW:新建事務(wù),如果當前在事務(wù)中,把當前事務(wù)掛起。

  • NOT_SUPPORTED:以非事務(wù)方式執(zhí)行操作,如果當前存在事務(wù),就把當前事務(wù)掛起

  • NEVER:以非事務(wù)方式運行,如果當前存在事務(wù),拋出異常

  • NESTED:如果當前存在事務(wù),則在嵌套事務(wù)內(nèi)執(zhí)行。如果當前沒有事務(wù),則執(zhí)行 REQUIRED 類似的操作

  • 超時時間:默認值是-1,沒有超時限制。如果有,以秒為單位進行設(shè)置

  • 是否只讀:建議查詢時設(shè)置為只讀

1.3 TransactionStatus

TransactionStatus 接口提供的是事務(wù)具體的運行狀態(tài),方法介紹如下。

4.png

1.4 知識要點

編程式事務(wù)控制三大對象

  • PlatformTransactionManager

  • TransactionDefinition

  • TransactionStatus

2 基于 XML 的聲明式事務(wù)控制

2.1 什么是聲明式事務(wù)控制

Spring 的聲明式事務(wù)顧名思義就是采用聲明的方式來處理事務(wù)。這里所說的聲明,就是指在配置文件中聲明,用在 Spring 配置文件中聲明式的處理事務(wù)來代替代碼式的處理事務(wù)。

聲明式事務(wù)處理的作用

  • 事務(wù)管理不侵入開發(fā)的組件。具體來說,業(yè)務(wù)邏輯對象就不會意識到正在事務(wù)管理之中,事實上也應(yīng)該如此,因為事務(wù)管理是屬于系統(tǒng)層面的服務(wù),而不是業(yè)務(wù)邏輯的一部分,如果想要改變事務(wù)管理策劃的話,也只需要在定義文件中重新配置即可

  • 在不需要事務(wù)管理的時候,只要在設(shè)定文件上修改一下,即可移去事務(wù)管理服務(wù),無需改變代碼重新編譯,這樣維護起來極其方便

注意:Spring 聲明式事務(wù)控制底層就是AOP。

2.2 聲明式事務(wù)控制的實現(xiàn)

聲明式事務(wù)控制明確事項:

  • 誰是切點?

  • 誰是通知?

  • 配置切面?

準備好controller,service,dao,domain和maven的jar包

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>nono_spring_tx</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.4</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.32</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

</project>
package com.nono.controller;

import com.nono.service.AccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AccountController {

    public static void main(String[] args) {
        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        AccountService accountService = app.getBean(AccountService.class);
        accountService.transfer("tom","Jerry",500);
    }

}

package com.nono.service.impl;

import com.nono.dao.AccountDao;
import com.nono.service.AccountService;

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);
    }
}

package com.nono.dao.impl;

import com.nono.dao.AccountDao;
import org.springframework.jdbc.core.JdbcTemplate;

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);
    }
}


①引入tx命名空間

<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">


②配置事務(wù)增強

<!--平臺事務(wù)管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"></property>
</bean>

<!--事務(wù)增強配置-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="*"/>
    </tx:attributes>
</tx:advice>

③配置事務(wù) AOP 織入

<!--事務(wù)的aop增強-->
    <aop:config>                                  
        <aop:pointcut id="myPointcut" expression="execution(* com.nono.service.impl.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="myPointcut"></aop:advisor>
    </aop:config>

<?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: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">


    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/nono"></property>
        <property name="user" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>

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


    <bean id="accountDao" class="com.nono.dao.impl.AccountDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"></property>
    </bean>

    <!--目標對象  內(nèi)部的方法就是切點-->
    <bean id="accountService" class="com.nono.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>

    <!--配置平臺事務(wù)管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--事務(wù)增強配置-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>

    <!--事務(wù)的aop增強-->
    <aop:config>
        <aop:pointcut id="myPointcut" expression="execution(* com.nono.service.impl.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="myPointcut"></aop:advisor>
    </aop:config>

</beans>

④測試事務(wù)控制轉(zhuǎn)賬業(yè)務(wù)代碼

@Override
public void transfer(String outMan, String inMan, double money) {
    accountDao.out(outMan,money);
    int i = 1/0;
    accountDao.in(inMan,money);
}

2.3 切點方法的事務(wù)參數(shù)的配置

<!--事務(wù)增強配置-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="*"/>
    </tx:attributes>
</tx:advice>

其中,<tx:method> 代表切點方法的事務(wù)參數(shù)的配置,例如:

<tx:method name="transfer" isolation="REPEATABLE_READ" propagation="REQUIRED" timeout="-1" read-only="false"/>
  • name:切點方法名稱

  • isolation:事務(wù)的隔離級別

  • propogation:事務(wù)的傳播行為

  • timeout:超時時間

  • read-only:是否只讀

<!--事務(wù)增強配置-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*"/>
            <tx:method name="transfer" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
            <tx:method name="save" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
            <tx:method name="findAll" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true"/>
            <tx:method name="update*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true"/>
        </tx:attributes>
    </tx:advice>

2.4 知識要點

聲明式事務(wù)控制的配置要點

  • 平臺事務(wù)管理器配置

  • 事務(wù)通知的配置

  • 事務(wù)aop織入的配置

3 基于注解的聲明式事務(wù)控制

3.1 使用注解配置聲明式事務(wù)控制

  1. 編寫 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);
    }
}
  1. 編寫 AccoutService
@Service("accountService")
@Transactional
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);
    }
}
  1. 編寫 applicationContext.xml 配置文件
<!—之前省略datsSource、jdbcTemplate、平臺事務(wù)管理器的配置-->
<!--組件掃描-->
<context:component-scan base-package="com.nono"/>
<!--事務(wù)的注解驅(qū)動-->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>

3.2 注解配置聲明式事務(wù)控制解析

①使用 @Transactional 在需要進行事務(wù)控制的類或是方法上修飾,注解可用的屬性同 xml 配置方式,例如隔離級別、傳播行為等。

②注解使用在類上,那么該類下的所有方法都使用同一套注解參數(shù)配置。

③使用在方法上,不同的方法可以采用不同的事務(wù)參數(shù)配置。

④Xml配置文件中要開啟事務(wù)的注解驅(qū)動<tx:annotation-driven />

3.3 知識要點

注解聲明式事務(wù)控制的配置要點

  • 平臺事務(wù)管理器配置(xml方式)

  • 事務(wù)通知的配置(@Transactional注解配置)

  • 事務(wù)注解驅(qū)動的配置 <tx:annotation-driven/>

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容