Spring Framework (XIII): spring declarative transaction control

A, spring transaction control API

1、PlatformTransactionManager

1.1, the role of: providing a common method of operation of its services.

1.2, commonly used methods:

  • TransactionStatus getTransaction (TransactionDefinition definition): Gets the transaction status information
  • void commit (TransactionStatus status): commit the transaction
  • void rollback (TransactionStatus status): roll back the transaction

2、TransactionDefinition

2.1 Role: to provide transaction definition information

2.2, commonly used methods:

  • String getName (): Gets the name of the transaction object
  • int getPropagationBehavior (): Gets propagation behavior Affairs
  • int getIsolationLevel (): Gets the transaction isolation level
  • int getTimeout (): Gets the transaction timeout
  • boolean isReadOnly (): Gets whether the transaction is read-only

3、TransactionStatus

3.1, the role of: providing a specific operating state of affairs

3.2, commonly used methods:

  • boolean isNewTransaction (): Gets whether the transaction is a new transaction
  • boolean hasSavepoint (): Get the point whether or not there reservoir
  • void setRollbackOnly (): Set transaction rollback
  • boolean isRollbackOnly (): Gets whether the transaction is rolled back
  • boolean isCompleted (): Gets whether the transaction is completed
  • void flush (): Refresh Affairs

Second, the xml-based declarative transaction control

1, create a maven project and import coordinate jar package

2. Create an account at a domain entity class Account package

package com.wedu.spring13.domain;

import java.io.Serializable;

/**
 * 账户实体
 */
public class Account implements Serializable{

    private Integer id;
    private Integer uid;
    private Double money;

    public Integer getId() {
        return id;
    }

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

    public Integer getUid() {
        return uid;
    }

    public void setUid(Integer uid) {
        this.uid = uid;
    }

    public Double getMoney() {
        return money;
    }

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

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

3, create a persistent layer interface at IAccountDao package and a method of adding dao

package com.wedu.spring13.dao;

import com.wedu.spring13.domain.Account;

import java.util.List;

/**
 * 账户持久层接口
 */
public interface IAccountDao {

    /**
     * 查询所有账户
     * @return
     */
    List<Account> findAllAccount();


    /**
     * 修改账户
     * @param account
     */
    void updateAccount(Account account);

    /**
     * 根据id查询账户
     * @param id
     * @return
     */
    Account findAccountById(Integer id);
}

4, create a class that implements the interface persistence layer AccountDaoImpl in the package and implement methods dao

package com.wedu.spring13.dao.impl;

import com.wedu.spring13.dao.IAccountDao;
import com.wedu.spring13.domain.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import java.util.List;

/**
 * 账户持久层接口实现
 */
public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {

    @Override
    public List<Account> findAllAccount() {
        return super.getJdbcTemplate().query("select * from account",new BeanPropertyRowMapper<Account>(Account.class));
    }

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

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

5, create the business service layer interface at IAccountService package and a method of adding

package com.wedu.spring13.service;

import com.wedu.spring13.domain.Account;

import java.util.List;

/**
 * 账户业务层接口
 */
public interface IAccountService {

    /**
     * 查询所有账户
     * @return
     */
    List<Account> findAllAccount();


    /**
     * 修改账户
     * @param account
     */
    void updateAccount(Account account);

    /**
     * 根据id查询账户
     * @param id
     * @return
     */
    Account findAccountById(Integer id);

    /**
     * 转账业务
     * @param sourceId 转出账户
     * @param targetId 转入账户
     * @param money 转账金额
     */
    void transfer(Integer sourceId, Integer targetId, Double money);
}

6、在service包下创建业务层接口的实现类AccountServiceImpl并实现方法

package com.wedu.spring13.service.impl;

import com.wedu.spring13.dao.IAccountDao;
import com.wedu.spring13.domain.Account;
import com.wedu.spring13.service.IAccountService;

import java.util.List;

/**
 * 账户业务层接口实现
 */
public class AccountServiceImpl implements IAccountService {

    private IAccountDao accountDao;

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

    @Override
    public List<Account> findAllAccount() {
        return accountDao.findAllAccount();
    }

    @Override
    public void updateAccount(Account account) {
        accountDao.updateAccount(account);
    }

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

    @Override
    public void transfer(Integer sourceId, Integer targetId, Double money) {
        //1、根据id查询转出账户
        Account source = accountDao.findAccountById(sourceId);
        //2、根据id查询转入账户
        Account target = accountDao.findAccountById(targetId);
        //3、设置转出金额
        source.setMoney(source.getMoney() - money);
        //4、设置转入金额
        target.setMoney(target.getMoney() + money);
        //5、更新转出账户
        accountDao.updateAccount(source);

        //int i = 1/0;

        //6、更新转入账户
        accountDao.updateAccount(target);
    }
}

7、在resources下创建配置文件bean.xml并配置spring ioc和aop及事务

<?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.wedu.spring13.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"/>
    </bean>

    <!--配置dao-->
    <bean id="accountDao" class="com.wedu.spring13.dao.impl.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--配置数据源-->
    <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/test?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf8"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>

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

    <!--配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--配置事务的属性-->
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED" read-only="false" />
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
        </tx:attributes>
    </tx:advice>

    <!--配置aop-->
    <aop:config>
        <!-- 配置切入点表达式-->
        <aop:pointcut id="pt1" expression="execution(* com.wedu.spring13.service.impl.*.*(..))"/>
        <!--建立切入点表达式和事务通知的对应关系 -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
    </aop:config>
</beans>

8、在测试模块中创建测试类AccountServiceTest并编写转账业务测试方法

package com.wedu.spring13.service;

import com.wedu.spring13.domain.Account;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

/**
 * 基于xml的spring声明式事务控制测试
 */
public class AccountServiceTest {

    private IAccountService accountService;

    @Before
    public void init() {
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        accountService = ac.getBean("accountService", IAccountService.class);
    }

    /**
     * 查询所有账户
     */
    @Test
    public void testFindAllAccount() {
        List<Account> accounts = accountService.findAllAccount();
        for (Account account : accounts) {
            System.out.println(account);
        }
    }

    /**
     * 转账
     */
    @Test
    public void testTransfer() {
        accountService.transfer(1,2,100d);
    }
}

三、基于注解的声明式事务控制

1、创建maven项目并导入jar包的坐标

2、在domain包下创建账户实体类Account

package com.wedu.spring14.domain;

import java.io.Serializable;

/**
 * 账户实体
 */
public class Account implements Serializable{

    private Integer id;
    private Integer uid;
    private Double money;

    public Integer getId() {
        return id;
    }

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

    public Integer getUid() {
        return uid;
    }

    public void setUid(Integer uid) {
        this.uid = uid;
    }

    public Double getMoney() {
        return money;
    }

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

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

3、在dao包下创建持久层接口IAccountDao并添加方法

package com.wedu.spring14.dao;

import com.wedu.spring14.domain.Account;

import java.util.List;

/**
 * 账户持久层接口
 */
public interface IAccountDao {

    /**
     * 查询所有账户
     * @return
     */
    List<Account> findAllAccount();


    /**
     * 修改账户
     * @param account
     */
    void updateAccount(Account account);

    /**
     * 根据id查询账户
     * @param id
     * @return
     */
    Account findAccountById(Integer id);
}

4、在dao包下创建持久层接口的实现类AccountDaoImpl并实现方法

package com.wedu.spring14.dao.impl;

import com.wedu.spring14.dao.IAccountDao;
import com.wedu.spring14.domain.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 账户持久层接口实现
 */
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<Account> findAllAccount() {
        return jdbcTemplate.query("select * from account",new BeanPropertyRowMapper<Account>(Account.class));
    }

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

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

5、在service包下创建业务层接口IAccountService并添加方法

package com.wedu.spring14.service;

import com.wedu.spring14.domain.Account;

import java.util.List;

/**
 * 账户业务层接口
 */
public interface IAccountService {

    /**
     * 查询所有账户
     * @return
     */
    List<Account> findAllAccount();


    /**
     * 修改账户
     * @param account
     */
    void updateAccount(Account account);

    /**
     * 根据id查询账户
     * @param id
     * @return
     */
    Account findAccountById(Integer id);

    /**
     * 转账业务
     * @param sourceId 转出账户
     * @param targetId 转入账户
     * @param money 转账金额
     */
    void transfer(Integer sourceId, Integer targetId, Double money);
}

6、在service包下创建业务层接口的实现类AccountServiceImpl并实现方法

package com.wedu.spring14.service.impl;

import com.wedu.spring14.dao.IAccountDao;
import com.wedu.spring14.domain.Account;
import com.wedu.spring14.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 账户业务层接口实现
 */
@Service("accountService")
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)//只读型事务的配置
public class AccountServiceImpl implements IAccountService {

    @Autowired
    private IAccountDao accountDao;

    @Override
    public List<Account> findAllAccount() {
        return accountDao.findAllAccount();
    }

    @Override
    public void updateAccount(Account account) {
        accountDao.updateAccount(account);
    }

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

    @Transactional(propagation = Propagation.REQUIRED,readOnly = false)//读写型事务的配置
    @Override
    public void transfer(Integer sourceId, Integer targetId, Double money) {
        //1、根据id查询转出账户
        Account source = accountDao.findAccountById(sourceId);
        //2、根据id查询转入账户
        Account target = accountDao.findAccountById(targetId);
        //3、设置转出金额
        source.setMoney(source.getMoney() - money);
        //4、设置转入金额
        target.setMoney(target.getMoney() + money);
        //5、更新转出账户
        accountDao.updateAccount(source);

        //int i = 1/0;

        //6、更新转入账户
        accountDao.updateAccount(target);
    }
}

7、在resources下创建配置文件bean.xml并配置spring ioc和aop及事务

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

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

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

    <!--配置数据源-->
    <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/test?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf8"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>

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

    <!--开启spring对注解事务的支持-->
    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

8、在测试模块中创建测试类AccountServiceTest并编写转账业务测试方法

package com.wedu.spring14.service;

import com.wedu.spring14.domain.Account;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

/**
 * 基于注解的spring声明式事务控制测试
 */
public class AccountServiceTest {

    private IAccountService accountService;

    @Before
    public void init() {
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        accountService = ac.getBean("accountService", IAccountService.class);
    }

    /**
     * 查询所有账户
     */
    @Test
    public void testFindAllAccount() {
        List<Account> accounts = accountService.findAllAccount();
        for (Account account : accounts) {
            System.out.println(account);
        }
    }

    /**
     * 转账
     */
    @Test
    public void testTransfer() {
        accountService.transfer(1,2,100d);
    }
}
发布了134 篇原创文章 · 获赞 10 · 访问量 7348

Guess you like

Origin blog.csdn.net/yu1755128147/article/details/103855094