JAVA编程121——Spring事务管理

本文详细介绍了一个基于Spring框架的事务管理实战案例,包括Maven配置、Spring配置、实体类定义、DAO层、Service层及测试类的实现。通过转账业务场景,展示了如何利用Spring AOP和声明式事务控制进行数据库操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、目录结构

在这里插入图片描述

二、代码详解

1、maven配置文件:pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.mollen</groupId>
    <artifactId>spring_day04_transaction</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>
        
	<!--Spring DI核心依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
	<!--Spring jdbc依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>

        <!--SpringAOP 相关依赖-->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.7</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <target>1.8</target>
                    <source>1.8</source>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

2、spring配置文件:beans.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:context="http://www.springframework.org/schema/context"
       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/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--加载属性文件/自动寻找${}标记的属性并对应-->
    <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>

    <!--配置数据源-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

    <!--配置dao-->
    <bean id="accountDao" class="com.mollen.dao.impl.AccountDaoImpl">
        <property name="jdbcTemplate" ref="jdbaTamplate"></property>
    </bean>

    <!--配置service-->
    <bean id="accountService" class="com.mollen.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>

    <!--配置jdbctemplate-->
    <bean id="jdbaTamplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <constructor-arg name="dataSource" ref="dataSource"></constructor-arg>
    </bean>

    <!--配置声明式事物控制/Spring事务控制需要传入一个数据源dataSource-->
    <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="get*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="find*" propagation="REQUIRED" read-only="true"/>

            <!--添加相关-->
            <tx:method name="add*" propagation="REQUIRED"/>
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="insert*" propagation="REQUIRED"/>

            <!--修改相关-->
            <tx:method name="update*" propagation="REQUIRED"/>

            <!--删除相关-->
            <tx:method name="del*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="remove*" propagation="REQUIRED"/>

        </tx:attributes>
    </tx:advice>

    <!--SpringAOP配置-->
    <aop:config>
        <!--配置切入点,一般在业务层-->
        <aop:pointcut id="txPointCut" expression="execution(* com.mollen.service.impl.*.*(..))"/>
        <!--建立切入点表达式和事务通知之间的关系-->
        <aop:advisor advice-ref="txAdvice"  pointcut-ref="txPointCut"/>
    </aop:config>

</beans>
3、创建实体类:Account.java
package com.mollen.bean;

public class Account {

    private int id ;
    private String name ;
    private double money ;

    public Account() {
    }

    public Account(String name, double money) {
        this.id = id;
        this.name = name;
        this.money = money;
    }

   //getter/setter...

4、dao层:

1、dao层接口:AccountDao.java

package com.mollen.dao;

import com.mollen.bean.Account;

import java.sql.SQLException;

public interface AccountDao {

    /**
     * 根据用户名称查询用户信息
     * @param name
     * @return
     */
    Account findByName(String name) throws SQLException;

    /**
     * 更新账户信息
     * @param source
     */
    void update(Account source) throws SQLException;

    /**
     * 添加账户
     * @param account
     */
    void add(Account account);
}

2、dao接口实现类:AccountDaoImpl.java

package com.mollen.dao.impl;

import com.mollen.bean.Account;
import com.mollen.dao.AccountDao;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import java.sql.SQLException;

public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {

    @Override
    public Account findByName(String name) throws SQLException {
        String sql = "select * from account where name = ? ";
        try {
            return getJdbcTemplate().queryForObject(sql, new BeanPropertyRowMapper<Account>(Account.class), name);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        return  null ;
    }

    @Override
    public void update(Account account) throws SQLException {
        String sql = "update account set money = ? where name = ? ";
        getJdbcTemplate().update(sql,account.getMoney(),account.getName());
    }

    @Override
    public void add(Account account) {
        String sql = "insert into account values(null,?,?)";
        getJdbcTemplate().update(sql,account.getName(),account.getMoney());
    }
}

5、service层

1、service层接口:AccountService.java

package com.mollen.service;

import com.mollen.bean.Account;

import java.sql.SQLException;

public interface AccountService {

    /**
     * 转账业务功能
     * @param sourceName  转出账户
     * @param targetName  转入账户
     * @param money         转账金额
     * @throws SQLException
     */
    public void transfer(String sourceName, String targetName, double money) throws SQLException;

    /**
     * 添加账户信息
     * @param account
     */
    public void add(Account account);

}

2、service层接口实现类

package com.mollen.service.impl;

import com.mollen.bean.Account;
import com.mollen.dao.AccountDao;
import com.mollen.service.AccountService;

import java.sql.SQLException;

public class AccountServiceImpl implements AccountService {

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

    /**
     *  1、转账业务
     * @param sourceName  转出账户
     * @param targetName  转入账户
     * @param money         转账金额
     * @throws SQLException
     */
    @Override
    public void transfer(String sourceName, String targetName, double money) throws SQLException {
        //1.根据名称查询转出账户
        Account source = accountDao.findByName(sourceName);
        //1.1.转出账户减钱
        source.setMoney(source.getMoney()-money);
        //1.2.更新转出账户余额
        accountDao.update(source);

        //int i = 10 / 0 ;
        //2.根据名称查询转入账户
        Account target = accountDao.findByName(targetName);
        //2.1 转入账户加钱
        target.setMoney(target.getMoney()+money);
        //2.2 更新转入账户余额
        accountDao.update(target);
    }


    /**
     * 2、添加业务
     * @param account
     */
    @Override
    public void add(Account account) {
        account = new Account("ddd",1000);
        accountDao.add(account);
    }

}

6、编写测试类:AccountServiceTest.java
package com.mollen.service;

import com.mollen.bean.Account;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.sql.SQLException;

public class AccountServiceTest {

    private AccountService accountService ;
    //初始化
    @Before
    public void init(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:beans.xml");
        accountService = (AccountService)applicationContext.getBean("accountService");
    }

    //转账测试
    @Test
    public void transfer() throws SQLException {
        accountService.transfer("aaa","bbb",100);
    }

    //添加测试
    @Test
    public void add() throws SQLException {
        Account account = new Account("ddd",100);
        accountService.add(account);
    }
    
    //销毁
    @After
    public void destory(){

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值