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