Spring中的事務控制

我們都知道在JavaEE中事務管理處於業務層,在Spring中爲我們提供了一個jar包spring-tx用於事務控制。spring的事務控制是基於AOP的,它可以通過編程方式配置方式兩種方式來實現。

Spring的核心API

在這裏插入圖片描述

基於XML的事務控制案例

導入jar包

 <!--用於解析切入點表達式的jar包-->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.5</version>
            <scope>runtime</scope>
        </dependency>
        <!--Spring事務管理的jar包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.2.2.RELEASE</version>
        </dependency>
        <!--Spring jdbcTemplate所需的jar包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.2.RELEASE</version>
        </dependency>
        <!--Spring開發包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.2.RELEASE</version>
        </dependency>
        <!--用於數據庫的連接-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.18</version>
        </dependency>
        <!--用於測試-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

創建數據表,建立實體類

create table account(
	id int primary key auto_increment,
	name varchar(40),
	money float
)character set utf8 collate utf8_general_ci;

insert into account(name,money) values('熊大',5000);
insert into account(name,money) values('熊二',5000);
insert into account(name,money) values('光頭強',1000);
/**
 * 賬戶實體類
 */
public class Account implements Serializable {

    private int id;
    private String name;
    private float money;

    public int getId() {
        return id;
    }

    public void setId(int 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 +
                '}';
    }
}

編寫持久層接口及其實體類

/**
 * 持久層接口
 */
public interface AccountDao {

    /**
     * 更新賬戶
     * @param account
     */
    void updateAccount(Account account);

    /**
     * 通過賬戶名稱查找賬戶信息
     * @param name
     * @return
     */
    Account findAccountByName(String name);

}
/**
 * 持久層接口實現類
 */
public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {

    public void updateAccount(Account account) {
        super.getJdbcTemplate().update("update account set name=?, money=? where id=?",account.getName(),account.getMoney(),account.getId());
    }

    public Account findAccountByName(String name) {
        return super.getJdbcTemplate().queryForObject("select *from account where name=?",new BeanPropertyRowMapper<Account>(Account.class),name);
    }

}

編寫業務層接口及其實體類

/**
 * 業務層接口
 */
public interface AccountService {

    /**
     * 轉賬
     * @param sourceName  轉出賬目名稱
     * @param targetName 轉入賬戶名稱
     * @param money  轉賬金額
     */
    void transfer(String sourceName, String targetName, Float money);

}
public class AccountServiceImpl implements AccountService{

    public AccountDao accountDao;

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

    public void transfer(String sourceName, String targetName, Float money) {
        //獲取轉賬賬戶
        Account source = accountDao.findAccountByName(sourceName);
        Account target = accountDao.findAccountByName(targetName);
        //進行轉賬
        source.setMoney(source.getMoney()-money);
        target.setMoney(target.getMoney()+money);
        //更新賬戶
        accountDao.updateAccount(source);
        int i = 1 / 0;
        accountDao.updateAccount(target);
    }
}

編寫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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!-- 配置業務層-->
    <bean id="accountService" class="com.liang.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>

    <!-- 配置賬戶的持久層-->
    <bean id="accountDao" class="com.liang.dao.impl.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 配置數據源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/mySpring?serverTimezone=UTC"></property>
        <property name="username" value="root"></property>
        <property name="password" value="liang"></property>
    </bean>

    <!-- spring中基於XML的聲明式事務控制配置步驟
        1、配置事務管理器
        2、配置事務的通知
                此時我們需要導入事務的約束 tx名稱空間和約束,同時也需要aop的
                使用tx:advice標籤配置事務通知
                    屬性:
                        id:給事務通知起一個唯一標識
                        transaction-manager:給事務通知提供一個事務管理器引用
        3、配置AOP中的通用切入點表達式
        4、建立事務通知和切入點表達式的對應關係
        5、配置事務的屬性
               是在事務的通知tx:advice標籤的內部
     -->
<!--  配置事務管理器 -->
    <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>
            <!--name:指定方法名稱(業務核心方法)
                read-only:是否是隻讀事務,默認值爲false
                isolation:指定事務的隔離級別,默認值爲當前使用數據庫的默認隔離級別
                propagation:指定事務的傳播行爲
                timeout:指定超時時間,默認值爲-1(用於超時)
                rollback-for:用於指定一個異常,當執行產生該異常時,事務回滾;產生其他異常時,事務不回滾,沒有默認值時,任何異常都回滾
                no-rokkback-for:用於指定一個異常,當執行產生該異常時,事務不回滾;產生其他異常時,事務回滾,沒有默認值時,任何異常都回滾
            -->
            <tx:method name="*" propagation="REQUIRED" read-only="false"/>
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"></tx:method>
        </tx:attributes>
    </tx:advice>

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

編寫測試類進行測試

/**
 * 測試類
 */
public class TransferTest{

    private AccountService accountService;

    @Before
    public void init()
    {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
        accountService = (AccountService) applicationContext.getBean("accountService");
    }

    @Test
    public void testTransfer ()
    {
        accountService.transfer("熊大","熊二",100f);
    }

}

XML結合註解的配置方式

修改持久層接口實現類

/**
 * 持久層接口實現類
 */
@Repository(value = "accountDao")
public class AccountDaoImpl  implements AccountDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

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

    public Account findAccountByName(String name) {
        return jdbcTemplate.queryForObject("select *from account where name=?",new BeanPropertyRowMapper<Account>(Account.class),name);
    }

}

修改業務層接口實現類

@Service(value = "accountService")
public class AccountServiceImpl implements AccountService{

    @Autowired
    public AccountDao accountDao;

    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public void transfer(String sourceName, String targetName, Float money) {
        //獲取轉賬賬戶
        Account source = accountDao.findAccountByName(sourceName);
        Account target = accountDao.findAccountByName(targetName);
        //進行轉賬
        source.setMoney(source.getMoney()-money);
        target.setMoney(target.getMoney()+money);
        //更新賬戶
        accountDao.updateAccount(source);
        int i = 1 / 0;
        accountDao.updateAccount(target);
    }
}

修改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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <!--Spring掃描-->
    <context:component-scan base-package="com.liang"></context:component-scan>

    <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.cj.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/mySpring?serverTimezone=UTC"></property>
        <property name="username" value="root"></property>
        <property name="password" value="liang"></property>
    </bean>

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

    <!--開啓Spring對註解事務的支持-->
    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

純註解的配置方式(刪除XML配置文件)

導入jar包

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.2.RELEASE</version>
            <scope>test</scope>
        </dependency>

修改持久層接口實現類

/**
 * 持久層接口實現類
 */
@Repository(value = "accountDao")
public class AccountDaoImpl  implements AccountDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

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

    public Account findAccountByName(String name) {
        return jdbcTemplate.queryForObject("select *from account where name=?",new BeanPropertyRowMapper<Account>(Account.class),name);
    }

}

修改業務層接口實現類

@Service(value = "accountService")
public class AccountServiceImpl implements AccountService{

    @Autowired
    public AccountDao accountDao;

    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public void transfer(String sourceName, String targetName, Float money) {
        //獲取轉賬賬戶
        Account source = accountDao.findAccountByName(sourceName);
        Account target = accountDao.findAccountByName(targetName);
        //進行轉賬
        source.setMoney(source.getMoney()-money);
        target.setMoney(target.getMoney()+money);
        //更新賬戶
        accountDao.updateAccount(source);
        int i = 1 / 0;
        accountDao.updateAccount(target);
    }
}

編寫配置類以及連接數據庫文件

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mySpring?serverTimezone=UTC
jdbc.username=root
jdbc.password=liang
/**
 * 連接數據庫的配置類
 */
@PropertySource(value = "classpath:jdbc.properties")
public class JdbcConfig {

    @Value(value = "${jdbc.driver}")
    private String driver;
    @Value(value = "${jdbc.url}")
    private String url;
    @Value(value = "${jdbc.username}")
    private String username;
    @Value(value = "${jdbc.password}")
    private String password;


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

    @Bean(value = "dataSource")
    public DataSource createDataSource()
    {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }
}
/**
 * 事務配置類
 */
@EnableTransactionManagement
public class TransactionConfig {

    /**
     * 用於創建事務管理器對象
     * @param dataSource
     * @return
     */
    @Bean(value = "transactionManager")
    public PlatformTransactionManager createTransactionManager(DataSource dataSource)
    {
        return new DataSourceTransactionManager(dataSource);
    }
}
/**
 * 總配置類
 */
@Configuration
@ComponentScan(basePackages = "com.liang")
@Import({JdbcConfig.class,TransactionConfig.class})
public class SpringConfig {

}

修改測試類

/**
 * 測試類
 */
@RunWith(value = SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class JDbcTemplate {

    @Autowired
    private AccountService accountService;

    @Test
    public void testTransfer ()
    {
        accountService.transfer("熊大","熊二",100f);
    }

}
註解 功能
@Transactional 該註釋可以用在接口、類、方法上。用在接口上:表示該iek的所以實現類都有事務支持;用在類上;表示類中的所有方法都有事務支持;用在方法上:表示方法有事務支持。優先級:方法>類>接口
發佈了71 篇原創文章 · 獲贊 6 · 訪問量 5383
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章