spring提供的事务配置--纯注解

spring提供的事务--纯注解

 模拟转账业务  ,出错需要事务回滚,没错正常执行

 事务和数据库技术都是spring的内置提供的

--------dao包---------------

IAccountDao接口

package com.dao;

import com.domain.Account;

/**
 *
 * @date 2019/11/6 15:25 
 */
public interface IAccountDao {
    Account findAllById(Integer id);
    Account findAccountByName(String name);
    void updateAccount(Account account);
}
View Code

IAccountDao实现类

package com.dao.impl;

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

/**
 *  账户实现类
 * @date 2019/11/6 15:27
 */
@Repository("accountDao")
public class IAccountDaoImpl  implements IAccountDao {
    @Autowired
    private JdbcTemplate template;

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

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

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

--------domain包--------

domain类

package com.domain;

import java.io.Serializable;

/**
 * 
 * @date 2019/11/5 21:32
 */
public class Account implements Serializable {
    private Integer id;
    private String name;
    private Float money;

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + 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;
    }
}
View Code

--------service包---------------
IAccountService类

package com.service;

import com.domain.Account;

/**
 *  账户业务层
 * @date 2019/11/7 9:26
 */
public interface IAccountService {
    //根据id查询账户信息
    Account findAllById(Integer integer);
    /*转账
    * 转出账户,转入账户,转账金额*/
    void transfer(String sourceName, String targetName, Float f);
}
View Code

AccountServiceImpl类

package com.service.impl;

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

/**
 * 账户的业务层实现类
 *
 * 事务控制应该都是在业务层
 */
@Service("accountService")
@Transactional
public class AccountServiceImpl implements IAccountService {
    @Autowired
    private IAccountDao accountDao;

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


    @Override
    public Account findAllById(Integer accountId) {
        return accountDao.findAllById(accountId);

    }


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

--------config包---------------

JdbcConfig类

package 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.DriverManagerDataSource;

import javax.sql.DataSource;

/**
 * 数据库配置类
 * @date 2019/11/7 15:10
 */
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;

    @Bean(name = "jdbcTemplate")
    public JdbcTemplate createTemplate(DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }
    @Bean(name = "dataSource")
    public DataSource createDatasource(){
        DriverManagerDataSource ds=new DriverManagerDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        return ds;
    }
}
JdbcConfig

SpringConfig类

package config;

import org.springframework.context.annotation.*;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * spring的配置类 相当于bean.xml
 * @date 2019/11/7 15:08
 */
@Configuration
@ComponentScan("com")  //扫描包
@Import({JdbcConfig.class,TransactionManager.class})
@PropertySource("jdbcConfig.properties")  //配置数据源
@EnableTransactionManagement   //开启注解支持
public class SpringConfig {
}
SpringConfig

TransactionManager类

package config;

import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

/**
 * 配置事务管理器
 * @date 2019/11/7 15:41
 */
public class TransactionManager {
    @Bean(name = "transactionManager")
    public PlatformTransactionManager createTransactionManager(DataSource source){
        return new DataSourceTransactionManager(source);
    }
}
View Code

--------配置文件---------------

jdbcConfig.properties配置文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db5
jdbc.username=root
jdbc.password=123
View Code

--------test包---------------

AccountServiceTest类

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

/**
 * 使用spring jdbcTemplate 和内置的事务管理实现转账的业务
 * 基于注解
 * @date 2019/11/7 9:44
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class AccountServiceTest {

    @Autowired
    private IAccountService as;

    @Test
    public  void testTransfer(){
        as.transfer("a","b",100f);
    }

}
View Code

支付宝到账100元!

 

 

 

 

 

猜你喜欢

转载自www.cnblogs.com/july7/p/11812883.html
今日推荐