十三、Spring声明式事务管理(基于纯注解)

基于纯注解的声明式事务管理,可以根据xml配置来一步步的理解改进
pom依赖

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.6.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.6.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.2.6.RELEASE</version>
        </dependency>

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

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.5</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
        </dependency>
    </dependencies>

实体类

package com.lp.domain;

import java.io.Serializable;

/**
 * 账户的实体类
 */
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 +
                '}';
    }
}

dao层实现类

package com.lp.dao.impl;

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

import java.util.List;

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

    @Autowired
    private JdbcTemplate jdbcTemplate;

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

    public Account findAccountByName(String accountName) {
        List<Account> accounts = jdbcTemplate.query("select * from account where name = ?",new BeanPropertyRowMapper<Account>(Account.class),accountName);
        if(accounts.isEmpty()){
            return null;
        }
        if(accounts.size()>1){
            throw new RuntimeException("结果集不唯一");
        }
        return accounts.get(0);
    }

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

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

service层实现类

package com.lp.service.impl;

import com.lp.dao.IAccountDao;
import com.lp.domain.Account;
import com.lp.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;

/**
 * 账户的业务层实现类
 * <p>
 * 事务控制应该都是在业务层
 */
@Service("accountService")
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class AccountServiceImpl implements IAccountService {

    @Autowired
    private IAccountDao accountDao;


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

    }


    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public void transfer(String sourceName, String targetName, Float money) {
        System.out.println("transfer....");
        //2.1根据名称查询转出账户
        Account source = accountDao.findAccountByName(sourceName);
        //2.2根据名称查询转入账户
        Account target = accountDao.findAccountByName(targetName);
        //2.3转出账户减钱
        source.setMoney(source.getMoney() - money);
        //2.4转入账户加钱
        target.setMoney(target.getMoney() + money);
        //2.5更新转出账户
        accountDao.updateAccount(source);

        int i = 1 / 0;

        //2.6更新转入账户
        accountDao.updateAccount(target);
        System.out.println("success!!!");
    }

    public List<Account> findAll() {
        return accountDao.findAll();
    }
}

基于纯注解配置我们需要配置类
主配置类

package com.lp.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * @Date 2020/5/31 13:28
 * @Author luopeng
 */
@Configuration
@ComponentScan("com.lp")
@Import(JdbcConfig.class)
//自动开启事务管理
@EnableTransactionManagement
@PropertySource("jdbcConfig.properties")
public class SpringConfig {
}

jdbc和DataSource的配置类

package com.lp.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;

/**
 * @Date 2020/5/31 13:30
 * @Author luopeng
 */
public class JdbcConfig {
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

//    创建JdbcTemplate,注入数据源
    @Bean("jdbcTemplate")
    public JdbcTemplate getJdbcTemplate(DataSource dataSource){

        return new JdbcTemplate(dataSource);
    }

//    创建数据源
    @Bean("dataSource")
    public DataSource getDataSource(){
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }

//    配置事务管理器
    @Bean("dtManager")
    public DataSourceTransactionManager getDatasourceTransactionManager(DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }

}

jdbc配置文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf-8&useSSL=false
jdbc.username=root
jdbc.password=962464

测试类

package com.lp.test;


import com.lp.config.SpringConfig;
import com.lp.domain.Account;
import com.lp.service.IAccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

/**
 * 使用Junit单元测试:测试我们的配置
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class AccountServiceTest {

    @Autowired
    @Qualifier("accountService")
    private  IAccountService as;

    @Test
    public  void testTransfer(){
        as.transfer("aaa","ccc",100f);


    }

    @Test
    public void testFindAll(){
        List<Account> all = as.findAll();
        for (Account account : all) {
            System.out.println(account);
    }}

}

dao接口和service接口代码不用贴出来了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring声明式事务管理包括以下几个步骤:1. 在 Spring 配置文件中配置事务管理器;2. 使用 @Transactional 注解将需要事务管理的方法标注;3. 调用该方法,Spring 将自动开启事务并在事务结束时自动提交或回滚事务。 ### 回答2: Spring声明式事务管理使用步骤如下: 1. 配置数据源:首先需要配置数据源,用于连接数据库。可以使用Spring提供的内置数据源或者自定义数据源。 2. 配置事务管理器:使用Spring的TransactionManager来配置事务管理器,可根据需要选择不同的事务管理器,如DataSourceTransactionManager、JpaTransactionManager等。 3. 配置事务切入点:通过使用Spring提供的AspectJ表达式或者自定义切入点选择需要应用事务管理的方法。 4. 配置事务通知:使用Spring的TransactionInterceptor类来配置事务通知。可以在方法执行前、执行后或者执行出现异常时应用事务管理。 5. 配置AOP代理:通过使用Spring的AOP配置,将事务通知织入到需要应用事务管理的方法中。 6. 测事务管理:在应用中调用需要应用事务的方法,并验证事务是否正确管理。 以上就是使用Spring声明式事务管理的步骤。通过配置数据源、事务管理器、事务切入点和事务通知来实现事务管理,并使用AOP代理将事务通知织入到方法中。最后可以进行测,验证事务是否正确管理。使用Spring声明式事务管理可以大大简化事务管理的工作,并提高代码的可维护性和可重用性。 ### 回答3: Spring声明式事务管理使用步骤如下: 1. 配置数据源:首先,在Spring的配置文件中配置数据库的连接信息,包括数据库驱动类、连接URL、用户名和密码等。 2. 配置事务管理器:在配置文件中配置事务管理器,Spring提供了多种事务管理器的实现,如基于JDBC的DataSourceTransactionManager、基于JTA的JtaTransactionManager等,选择合适的事务管理器并配置。 3. 配置事务通知:使用Spring事务通知功能,将需要事务管理的方法或者类标注上相应的注解,如@Transactional。这些被注解的方法或者类,在运行时会被Spring框架拦截并自动应用事务管理。 4. 配置事务属性:在注解中可以指定事务的传播行为、隔离级别、超时时间等属性,根据具体的业务需求进行配置。 5. 配置异常回滚策略:通过捕获和处理特定的异常,可以控制事务的回滚行为。可以使用注解中的rollbackFor属性指定需要回滚的异常类型。 6. 运行和测:完成以上配置后,可以运行和测应用程序。在方法调用时,被事务管理的方法将会受到事务拦截和控制。如果出现异常或者满足回滚条件,事务将会回滚,否则事务将会提交。 需要注意的是,Spring声明式事务管理是基于AOP实现的,在运行时使用代理对象对方法进行增强。配置声明式事务管理的步骤可以在Spring的配置文件中进行,也可以使用注解进行配置。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值