Spring框架(12) —— 事务管理案例

简介

  • 本文将在 Spring 框架中,分别使用使用“XML”,“XML+注释”和“注解+Java”三种方式来演示数据库的转账操作。

项目环境

数据库代码

  • 创建数据库spring,在数据库中创建 Account表。
# 创建数据库
CREATE DATABASE spring;

# 使用数据库
USE spring;

# 创建表
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('Cat',1000);
INSERT INTO account(NAME,money) VALUES('Dog',1000);
INSERT INTO account(NAME,money) VALUES('Rat',1000);

Maven依赖

pom.xml

    <dependencies>
        
        <!-- Spring 框架 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <!-- Spring AOP -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.7</version>
        </dependency>
        
        <!-- spring JDBC框架 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        
        <!-- Spring 事务管理 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        
        <!-- MySQL数据库驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        
        <!-- 【被 Spring JDBC 代替】 -->
        <!-- 数据库连接池 -->
<!--        <dependency>-->
<!--            <groupId>c3p0</groupId>-->
<!--            <artifactId>c3p0</artifactId>-->
<!--            <version>0.9.1.2</version>-->
<!--        </dependency>-->
        
        <!-- 【被 Spring JDBC 代替】 -->
        <!-- 操作数据库的工具包 -->
<!--        <dependency>-->
<!--            <groupId>commons-dbutils</groupId>-->
<!--            <artifactId>commons-dbutils</artifactId>-->
<!--            <version>1.4</version>-->
<!--        </dependency>-->
        
        <!-- Spring 测试 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        
        <!-- 单元测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        
    </dependencies>

Spring配置文件

<?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">
    
    
</beans>

实体类

Account.java

public class Account {

    /* 成员变量 */
    private int id;
    private String name;
    private float money;

    /* 构造函数 */
    public Account() {
    }

    public Account(int id, String name, float money) {
        this.id = id;
        this.name = name;
        this.money = 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;
    }

    /* toString方法 */
    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

持久层接口

AccountDao.java

public interface AccountDao {

    /** 查询所有 */
    List<Account> findAll();
    /** 查询单个 */
    Account findByID(int id);
    /** 添加 */
    void add(Account account);
    /** 修改 */
    void update(Account account);
    /** 删除 */
    void delete(int id);

}

业务层接口

AccountService.java

public interface AccountService {

    /** 转账 */
    void transfer(int sourceId, int targetId, float money);


}

测试类

junit

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import xml.service.AccountService;


public class SpringTest {

    /* 成员变量 */
    private ApplicationContext app;
    private AccountService service;

    @Before
    public void init(){
        app = new ClassPathXmlApplicationContext("xml/Beans.xml");
        service = app.getBean("serviceImp",AccountService.class);
    }

    /** 转账 */
    @Test
    public void test01() {
        service.transfer(1,2,10f);
    }

}

Spring整合junit

import java_anno.config.SpringConfiguration;
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;
import java_anno.service.AccountService;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class SpringTest {

    /* 成员变量 */
    @Autowired
    private AccountService service;


    /** 查询所有 */
    @Test
    public void test01() {
        service.transfer(1,2,10f);
    }


}

基于XML配置文件

此部分分为三部分

  • 目录结构:帮助了解整个项目的基本结构,以及完整详细的代码。
  • 依赖注入:此部分是本文着重比较的地方,单独分为一部分。
  • CURD操作:与Spring框架的核心内容关系不大,可作为延展内容。

目录结构

  • src
    • main
      • java
        • service
          • AccountServiceImp.java(业务层实现类)
        • dao
          • AccountDaoImp.java(持久层实习类)
      • resources
        • Beans.xml(Spring配置文件)

持久层实现类

  • 操作数据库
    • 继承 JdbcDaoSupport
    • 注入 DataSource

AccountDaoImp.java

package xml.dao;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import xml.domain.Account;

import java.util.List;


public class AccountDaoImp extends JdbcDaoSupport implements AccountDao {


    /** 查询所有 */
    public List<Account> findAll() {
        return super.getJdbcTemplate().query(
                /* SQL语句 */
                "SELECT * FROM account ",
                /* 结果集 */
                new BeanPropertyRowMapper<Account>(Account.class));
    }
    /** 查询单个 */
    public Account findByID(int id) {
        return super.getJdbcTemplate().queryForObject(
                /* SQL语句 */
                "SELECT * FROM account WHERE id = ? ",
                /* 结果集 */
                new BeanPropertyRowMapper<Account>(Account.class),
                id);
    }
    /** 添加 */
    public void add(Account account) {
        super.getJdbcTemplate().update(
                /* SQL语句 */
                "INSERT INTO account VALUES(?,?,?)",
                /* 参数 */
                account.getId(),
                account.getName(),
                account.getMoney());
    }
    /** 修改 */
    public void update(Account account) {
        super.getJdbcTemplate().update(
                /* SQL语句 */
                " UPDATE account SET name=?,money=? WHERE id=? ",
                /* 参数 */
                account.getName(),
                account.getMoney(),
                account.getId());
    }
    /** 删除 */
    public void delete(int id) {
        super.getJdbcTemplate().update(
                /* SQL语句 */
                " DELETE FROM account WHERE id=? ",
                /* 参数 */
                id);
    }


}

业务层实现类

  • 调用持久层方法
    • 基于xml的方式注入

AccountServiceImp.java

package xml.service;

import org.springframework.stereotype.Component;
import xml.dao.AccountDao;
import xml.domain.Account;

import javax.annotation.Resource;
import java.util.List;


public class AccountServiceImp implements AccountService {

    /* 成员变量 */
    private AccountDao dao;

    /* 设值函数 */
    public void setDao(AccountDao dao) {
        this.dao = dao;
    }

    /** 转账 */
    public void transfer(int sourceId, int targetId, float money) {
        Account source = dao.findByID(sourceId);
        Account target = dao.findByID(targetId);
        Float sourceMoney = source.getMoney();
        Float targetMoney = target.getMoney();
        source.setMoney(sourceMoney - money);
        dao.update(source);
//        int i = 10/0;
        target.setMoney(targetMoney + money);
        dao.update(target);
    }


}

配置文件

  • 依赖注入
  • 开启事务管理
    • AOP
    • TransactionManager

Beans.xml

    <!-- DataSource -->
   <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/spring"/>
       <property name="username" value="root"/>
       <property name="password" value="root"/>
   </bean>

    <!-- DaoImp -->
    <bean id="daoImp" class="xml.dao.AccountDaoImp">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- ServiceImp -->
    <bean id="serviceImp" class="xml.service.AccountServiceImp">
        <property name="dao" ref="daoImp"/>
    </bean>

    <!-- DataSourceTransactionManager -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>


    <!-- AOP -->
    <aop:config>
        <aop:pointcut id="all" expression="execution(* xml.service.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="all"/>
    </aop:config>

    <!-- tx -->
    <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>

基于XML配置文件和注解

目录结构

  • src
    • main
      • java
        • service
          • AccountServiceImp.java(业务层实现类)
        • dao
          • AccountDaoImp.java(持久层实习类)
      • resources
        • Beans.xml(Spring配置文件)

持久层实现类

  • 操作数据库
    • 注入 JdbcTemplate

AccountDaoImp.java

package xml_anno.dao;

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 xml_anno.domain.Account;

import java.util.List;


@Repository
public class AccountDaoImp implements AccountDao {

    /* 成员变量 */
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /** 查询所有 */
    public List<Account> findAll() {
        return jdbcTemplate.query(
                /* SQL语句 */
                "SELECT * FROM account ",
                /* 结果集 */
                new BeanPropertyRowMapper<Account>(Account.class));
    }
    /** 查询单个 */
    public Account findByID(int id) {
        return jdbcTemplate.queryForObject(
                /* SQL语句 */
                "SELECT * FROM account WHERE id = ? ",
                /* 结果集 */
                new BeanPropertyRowMapper<Account>(Account.class),
                id);
    }
    /** 添加 */
    public void add(Account account) {
        jdbcTemplate.update(
                /* SQL语句 */
                "INSERT INTO account VALUES(?,?,?)",
                /* 参数 */
                account.getId(),
                account.getName(),
                account.getMoney());
    }
    /** 修改 */
    public void update(Account account) {
        jdbcTemplate.update(
                /* SQL语句 */
                " UPDATE account SET name=?,money=? WHERE id=? ",
                /* 参数 */
                account.getName(),
                account.getMoney(),
                account.getId());
    }
    /** 删除 */
    public void delete(int id) {
        jdbcTemplate.update(
                /* SQL语句 */
                " DELETE FROM account WHERE id=? ",
                /* 参数 */
                id);
    }


}

业务层实现类

  • 调用持久层方法
    • 基于注解的方式注入
  • 开启事务支持
    • 基于注解的方式

AccountServiceImp.java

package xml_anno.service;

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 xml_anno.domain.Account;
import xml_anno.dao.AccountDao;


@Service
/** 事务支持(查询方法) */
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class AccountServiceImp implements AccountService {

    /* 成员变量 */
    @Autowired
    private AccountDao dao;

    /** 转账 */
    /** 事务支持(增删改方法) */
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
    public void transfer(int sourceId, int targetId, float money) {
        Account source = dao.findByID(sourceId);
        Account target = dao.findByID(targetId);
        Float sourceMoney = source.getMoney();
        Float targetMoney = target.getMoney();
        source.setMoney(sourceMoney - money);
        dao.update(source);
        int i = 10/0;
        target.setMoney(targetMoney + money);
        dao.update(target);
    }

}

配置文件

  • 依赖注入
  • 开启注解扫描

Beans.xml

    <!-- DataSource -->
    <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/spring"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>

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

    <!-- 开启注解扫描 -->
    <context:component-scan base-package="xml_anno"></context:component-scan>


基于Java配置文件和注解

目录结构

  • src
    • main
      • java
        • service
          • AccountServiceImp.java(业务层实现类)
        • dao
          • AccountDaoImp.java(持久层实习类)
        • config
          • SpringConfiguration.java(Java配置文件)
          • JdbcConfig.java(Java配置文件)
          • TransactionConfig.java(Java配置文件)

持久层实现类

AccountDaoImp.java

package java_anno.dao;

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.Component;
import org.springframework.stereotype.Repository;
import xml_anno.dao.AccountDao;
import xml_anno.domain.Account;

import java.util.List;


@Component
public class AccountDaoImp implements AccountDao {


        /* 成员变量 */
        @Autowired
        private JdbcTemplate jdbcTemplate;


        /** 查询所有 */
        public List<Account> findAll() {
            return jdbcTemplate.query(
                    /* SQL语句 */
                    "SELECT * FROM account ",
                    /* 结果集 */
                    new BeanPropertyRowMapper<Account>(Account.class));
        }
        /** 查询单个 */
        public Account findByID(int id) {
            return jdbcTemplate.queryForObject(
                    /* SQL语句 */
                    "SELECT * FROM account WHERE id = ? ",
                    /* 结果集 */
                    new BeanPropertyRowMapper<Account>(Account.class),
                    id);
        }
        /** 添加 */
        public void add(Account account) {
            jdbcTemplate.update(
                    /* SQL语句 */
                    "INSERT INTO account VALUES(?,?,?)",
                    /* 参数 */
                    account.getId(),
                    account.getName(),
                    account.getMoney());
        }
        /** 修改 */
        public void update(Account account) {
            jdbcTemplate.update(
                    /* SQL语句 */
                    " UPDATE account SET name=?,money=? WHERE id=? ",
                    /* 参数 */
                    account.getName(),
                    account.getMoney(),
                    account.getId());
        }
        /** 删除 */
        public void delete(int id) {
            jdbcTemplate.update(
                    /* SQL语句 */
                    " DELETE FROM account WHERE id=? ",
                    /* 参数 */
                    id);
        }


}

业务层实现类

AccountServiceImp.java

package java_anno.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import xml_anno.dao.AccountDao;
import xml_anno.domain.Account;


@Component
public class AccountServiceImp implements AccountService {

    /* 成员变量 */
    @Autowired
    private AccountDao dao;

    /** 转账 */
    /** 事务支持(增删改方法) */
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
    public void transfer(int sourceId, int targetId, float money) {
        xml_anno.domain.Account source = dao.findByID(sourceId);
        Account target = dao.findByID(targetId);
        Float sourceMoney = source.getMoney();
        Float targetMoney = target.getMoney();
        source.setMoney(sourceMoney - money);
        dao.update(source);
//        int i = 10/0;
        target.setMoney(targetMoney + money);
        dao.update(target);
    }

}

数据库连接工具类

jdbcConfig.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring
jdbc.username=root
jdbc.password=root

Spring配置文件

SpringConfiguration.java

package java_anno.config;

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


/** 指定配置文件 */
@Configuration
/** 开启注解扫描 */
@ComponentScan("java_anno")
/** 指定property文件 */
@PropertySource("classpath:java_anno/jdbcConfig.properties")
/** 设置子文件 */
@Import({JdbcConfig.class,TransactionConfig.class})
/** 开启事务管理器 */
@EnableTransactionManagement
public class SpringConfiguration {


}

数据库连接配置文件

JdbcConfig.java

package java_anno.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;
import java.sql.Driver;


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;

    /** DataSource */
    @Bean(name = "dataSource")
    public DataSource getDataSource(){
        DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
        driverManagerDataSource.setDriverClassName(driver);
        driverManagerDataSource.setUrl(url);
        driverManagerDataSource.setUsername(username);
        driverManagerDataSource.setPassword(password);
        return driverManagerDataSource;
    }

    /** JdbcTemplate */
    @Bean(name = "jdbc")
    public JdbcTemplate getJdbcTemplate(DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }


}

事务管理配置文件

TransactionConfig.java

package java_anno.config;

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

import javax.sql.DataSource;


public class TransactionConfig {

    /** TransactionManager */
    @Bean(name = "transactionManager")
    public PlatformTransactionManager getTransactionManager(DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }


}
发布了68 篇原创文章 · 获赞 2 · 访问量 1924

猜你喜欢

转载自blog.csdn.net/qq_40981851/article/details/104191840