Spring学习第四天:JdbcTemplate,spring中的事务

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,集群版 2核4GB 100GB
推荐场景:
搭建个人博客
云数据库 RDS MySQL,高可用版 2核4GB 50GB
简介: Spring学习第四天:JdbcTemplate,spring中的事务

JdbcTemplate

依赖项

除mysql驱动以外还需要以下两个jar包

    <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.10</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.3.10</version>
        </dependency>

其中spring-tx是事务控制相关的

最基本的使用

基本使用和c3p0和dbutils差别不大

    public static void main(String[] args) {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUsername("root");
        dataSource.setPassword("adminadmin");
        dataSource.setUrl("jdbc:mysql://localhost:3306/spring_test");
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        jdbcTemplate.execute("insert into account(name,money) values('ccc',123)");
    }

写到这里我们可以注意到这里有很多语句可以使用到spring中的IOC,那么下步我们就进行对spring的配置

JdbcTemplate的IOC配置:

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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="username" value="root"/>
        <property name="password" value="adminadmin"/>
        <property name="url" value="jdbc:mysql://localhost:3306/spring_test"/>
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
    </bean>
    <bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

主函数

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("Bean.xml");
        JdbcTemplate jdbcTemplate = (JdbcTemplate)context.getBean("jdbcTemplate");
        jdbcTemplate.execute("insert into account(name,money) values('ccc',123)");
    }

改成原来常用的Dao模式

创建接口:

package com.spring.dao;
import com.spring.beans.Account;
import java.util.List;
/**
 * @author 28985
 */
public interface IAccountDao {
    /**
     * 查找所有
     * @return
     */
    public List<Account> findAll();
    /**
     * 根据ID查找
     * @return
     */
    public Account findById(Integer id);
    /**
     * 更新
     * @param account
     */
    public void update(Account account);
    /**
     * 删除
     * @param id
     */
    public void delete(Integer id);
    /**
     * 插入
     * @param account
     */
    public void insert(Account account);
    /**
     * 大于多少钱的人数
     * @param money
     * @return
     */
    public Integer moneyNumber(Integer money);
}

创建其实现类:

package com.spring.dao.impl;
import com.spring.beans.Account;
import com.spring.dao.IAccountDao;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
/**
 * @author 28985
 */
public class AccountDao implements IAccountDao {
    private JdbcTemplate jdbcTemplate;
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    @Override
    public List<Account> findAll() {
        return jdbcTemplate.query("select * from account", new BeanPropertyRowMapper<Account>(Account.class));
    }
    @Override
    public Account findById(Integer id) {
        try {
            return jdbcTemplate.query("select * from account where id = ?", new BeanPropertyRowMapper<Account>(Account.class),id).get(0);
        }
        catch (Exception e){
            Account account =new Account();
            account.setName("NOTFOUND");
            return account;
        }
    }
    @Override
    public void update(Account account) {
        jdbcTemplate.update("update account set name = ?,money = ? where id = ?",account.getName(),account.getMoney(),account.getId());
    }
    @Override
    public void delete(Integer id) {
        jdbcTemplate.update("delete from account where id = ?",id);
    }
    @Override
    public void insert(Account account) {
        jdbcTemplate.update("insert into account(name,money) values(?,?)",account.getName(),account.getMoney());
    }
    @Override
    public Integer moneyNumber(Integer money) {
        return jdbcTemplate.queryForObject(" select count(*) from account where money > ? ", Integer.class, 900);
    }
}

再进行springIOC的配置即可使用

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean name="dao" class="com.spring.dao.impl.AccountDao">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>
    <bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="username" value="root"/>
        <property name="password" value="adminadmin"/>
        <property name="url" value="jdbc:mysql://localhost:3306/spring_test"/>
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
    </bean>
  <bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
  </bean>
</beans>

进行到这里,我们会发现一个问题,如果我们有多个dao接口的实现类,他们其中的

    private JdbcTemplate jdbcTemplate;
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

这段代码是重复的

此时我们便可以提取这段代码 创建AccountDaoSupper类

package com.spring.dao.impl;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
public class AccountDaoSupper {
    private JdbcTemplate jdbcTemplate;
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }
    public void setDatasource(DataSource dataSource){
        jdbcTemplate = new JdbcTemplate(dataSource);
    }
}

然后再创建dao时就可以extends AccountDaoSupper implements IAccountDao

对应的其中所有对jdbcTemplate都将改为getJdbcTemplate()

改后效果是这样的:

package com.spring.dao.impl;
import com.spring.beans.Account;
import com.spring.dao.IAccountDao;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
/**
 * @author 28985
 */
public class AccountDao extends AccountDaoSupper implements IAccountDao {
    @Override
    public List<Account> findAll() {
        return getJdbcTemplate().query("select * from account", new BeanPropertyRowMapper<Account>(Account.class));
    }
    @Override
    public Account findById(Integer id) {
        try {
            return getJdbcTemplate().query("select * from account where id = ?", new BeanPropertyRowMapper<Account>(Account.class),id).get(0);
        }
        catch (Exception e){
            Account account =new Account();
            account.setName("NOTFOUND");
            return account;
        }
    }
    @Override
    public void update(Account account) {
        getJdbcTemplate().update("update account set name = ?,money = ? where id = ?",account.getName(),account.getMoney(),account.getId());
    }
    @Override
    public void delete(Integer id) {
        getJdbcTemplate().update("delete from account where id = ?",id);
    }
    @Override
    public void insert(Account account) {
        getJdbcTemplate().update("insert into account(name,money) values(?,?)",account.getName(),account.getMoney());
    }
    @Override
    public Integer moneyNumber(Integer money) {
        return getJdbcTemplate().queryForObject(" select count(*) from account where money > ? ", Integer.class, 900);
    }
}

然后再进行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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean name="dao" class="com.spring.dao.impl.AccountDao">
        <property name="datasource" ref="dataSource"/>
    </bean>
    <bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="username" value="root"/>
        <property name="password" value="adminadmin"/>
        <property name="url" value="jdbc:mysql://localhost:3306/spring_test"/>
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
    </bean>
</beans>

但实际上AccountDaoSupper中的代码Spring已经为我们提供好了,我们删除掉AccountDaoSupper换成继承JdbcDaoSupport这时便可以实现相同功能,而无需创建AccountDaoSupper了

package com.spring.dao.impl;
import com.spring.beans.Account;
import com.spring.dao.IAccountDao;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import java.util.List;
/**
 * @author 28985
 */
public class AccountDao extends JdbcDaoSupport implements IAccountDao {
    @Override
    public List<Account> findAll() {
        return getJdbcTemplate().query("select * from account", new BeanPropertyRowMapper<Account>(Account.class));
    }
    @Override
    public Account findById(Integer id) {
        try {
            return getJdbcTemplate().query("select * from account where id = ?", new BeanPropertyRowMapper<Account>(Account.class),id).get(0);
        }
        catch (Exception e){
            Account account =new Account();
            account.setName("NOTFOUND");
            return account;
        }
    }
    @Override
    public void update(Account account) {
        getJdbcTemplate().update("update account set name = ?,money = ? where id = ?",account.getName(),account.getMoney(),account.getId());
    }
    @Override
    public void delete(Integer id) {
        getJdbcTemplate().update("delete from account where id = ?",id);
    }
    @Override
    public void insert(Account account) {
        getJdbcTemplate().update("insert into account(name,money) values(?,?)",account.getName(),account.getMoney());
    }
    @Override
    public Integer moneyNumber(Integer money) {
        return getJdbcTemplate().queryForObject(" select count(*) from account where money > ? ", Integer.class, 900);
    }
}

spring中的事务

在需要事务时我们可以使用spring-tx这个jar包来进行事务管理

那么先进行maven导包的配置

<?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>org.example</groupId>
    <artifactId>spring_day04_06TX_zhujie</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <packaging>jar</packaging>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.9</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.10</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.3.10</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.25</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.8.M1</version>
        </dependency>
    </dependencies>
</project>

首先我们先看看xml版本

首先最基本的当然是创建数据库封装的bean对象

package com.spring.beans;
/**
 * @author 28985
 */
public class Account {
    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 +
                '}';
    }
}

再来创建 持久层Dao的接口类

package com.spring.dao;
import com.spring.beans.Account;
import java.util.List;
/**
 * @author 28985
 */
public interface IAccountDao {
    /**
     * 查找所有
     * @return
     */
    public List<Account> findAll();
    /**
     * 根据ID查找
     * @return
     */
    public Account findById(Integer id);
    /**
     * 更新
     * @param account
     */
    public void update(Account account);
    /**
     * 删除
     * @param id
     */
    public void delete(Integer id);
    /**
     * 插入
     * @param account
     */
    public void insert(Account account);
    /**
     * 大于多少钱的人数
     * @param money
     * @return
     */
    public Integer moneyNumber(Integer money);
    /**
     * 根据名称查找账户
     * @param name
     * @return
     */
    public Account findByName(String name);
}

再来创建他的实现类AccountDao

package com.spring.dao.impl;
import com.spring.beans.Account;
import com.spring.dao.IAccountDao;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import java.util.List;
/**
 * @author 28985
 */
public class AccountDao extends JdbcDaoSupport implements IAccountDao {
    @Override
    public List<Account> findAll() {
        return getJdbcTemplate().query("select * from account", new BeanPropertyRowMapper<Account>(Account.class));
    }
    @Override
    public Account findById(Integer id) {
        try {
            return getJdbcTemplate().query("select * from account where id = ?", new BeanPropertyRowMapper<Account>(Account.class),id).get(0);
        }
        catch (Exception e){
            Account account =new Account();
            account.setName("NOTFOUND");
            return account;
        }
    }
    @Override
    public void update(Account account) {
        getJdbcTemplate().update("update account set name = ?,money = ? where id = ?",account.getName(),account.getMoney(),account.getId());
    }
    @Override
    public void delete(Integer id) {
        getJdbcTemplate().update("delete from account where id = ?",id);
    }
    @Override
    public void insert(Account account) {
        getJdbcTemplate().update("insert into account(name,money) values(?,?)",account.getName(),account.getMoney());
    }
    @Override
    public Integer moneyNumber(Integer money) {
        return getJdbcTemplate().queryForObject(" select count(*) from account where money > ? ", Integer.class, 900);
    }
    @Override
    public Account findByName(String name) {
        try {
            List<Account> query = getJdbcTemplate().query("select * from account where name = ?", new BeanPropertyRowMapper<Account>(Account.class), name);
            if (query.size()==1){
                return query.get(0);
            }
            else {
                return query.get(-1);
            }
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}

创建业务层接口

package com.spring.service;
import com.spring.beans.Account;
/**
 * 账户的业务层接口
 * @author 28985
 */
public interface IAccountService {
    /**
     *根据id查询账户
     * @param id
     * @return
     */
    Account findAccountById(Integer id);
    /**
     * 转账
     * @param sourceName 转出账户名
     * @param targetName 转入账户名称
     * @param money      转账金额
     */
    void transfer(String sourceName,String targetName,float money);
}

及业务层实现类

package com.spring.service.impl;
import com.spring.service.IAccountService;
import com.spring.beans.Account;
import com.spring.dao.IAccountDao;
/**
 * @author 28985
 */
public class AccountServiceImpl implements IAccountService {
    private IAccountDao accountDao;
    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }
    @Override
    public Account findAccountById(Integer id) {
        return accountDao.findById(id);
    }
    @Override
    public void transfer(String sourceName, String targetName, float money) {
        System.out.println("转账");
        Account sourceAccount = accountDao.findByName(sourceName);
        Account targetAccount = accountDao.findByName(targetName);
        sourceAccount.setMoney(sourceAccount.getMoney()-money);
        targetAccount.setMoney(targetAccount.getMoney()+money);
        accountDao.update(sourceAccount);
        int i= 1/0;
        accountDao.update(targetAccount);
    }
}

之后我们通过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
        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">
<!--    业务层-->
    <bean name="accountServiceImpl" class="com.spring.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="dao"/>
    </bean>
<!--    持久层-->
    <bean name="dao" class="com.spring.dao.impl.AccountDao">
        <property name="dataSource" ref="dataSource"/>
    </bean>
<!--    数据源-->
    <bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="username" value="root"/>
        <property name="password" value="adminadmin"/>
        <property name="url" value="jdbc:mysql://localhost:3306/spring_test"/>
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
    </bean>
</beans>

编写主函数:

package com.spring.jdbcTemplate;
import com.spring.service.IAccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class JdbcTemplate_test {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("Bean.xml");
        IAccountService service = (IAccountService) context.getBean("accountServiceImpl");
        service.transfer("aaa","bbb",200);
    }
}

此时执行主函数,会抛出异常,异常原因是因为业务层实现类里int i= 1/0;,而且会进行错误的转账,这时我们就可以添加事务进行解决了

修改bean.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
        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">
<!--    业务层-->
    <bean name="accountServiceImpl" class="com.spring.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="dao"/>
    </bean>
<!--    持久层-->
    <bean name="dao" class="com.spring.dao.impl.AccountDao">
        <property name="dataSource" ref="dataSource"/>
    </bean>
<!--    数据源-->
    <bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="username" value="root"/>
        <property name="password" value="adminadmin"/>
        <property name="url" value="jdbc:mysql://localhost:3306/spring_test"/>
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
    </bean>
<!--    配置事务管理器-->
    <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
<!--    配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!-- 配置事务的属性
        isolation:用于指定事务的隔离级别。默认值是DEFAULT,表示使用数据库的默认隔离级别。
        propagation:用于指定事务的传播行为。默认值是REQUIRED,表示一定会有事务,增删改的选择。查询方法可以选择SUPPORTS。
        read-only:用于指定事务是否只读。只有查询方法才能设置为true。默认值是false,表示读写。
        timeout:用于指定事务的超时时间,默认值是-1,表示永不超时。如果指定了数值,以秒为单位。
        rollback-for:用于指定一个异常,当产生该异常时,事务回滚,产生其他异常时,事务不回滚。没有默认值。表示任何异常都回滚。
        no-rollback-for:用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时事务回滚。没有默认值。表示任何异常都回滚。-->
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED" read-only="false"/>
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
        </tx:attributes>
    </tx:advice>
<!--    配置aop-->
    <aop:config>
<!--        配置切入点表达式-->
        <aop:pointcut id="pt1" expression="execution(* com.spring.service.impl.*.*(..))"/>
<!--        建立切入点表达式和事务通知的对应关系-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
    </aop:config>
</beans>

即可完成事务的配置,此时运行便可以得到正常的结果

再来看看注解的配置

修改原来xml的bean.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:context="http://www.springframework.org/schema/context"
       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
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 配置spring创建容器时要扫描的包-->
    <context:component-scan base-package="com.spring"></context:component-scan>
<!--    业务层-->
    <bean name="accountServiceImpl" class="com.spring.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="dao"/>
    </bean>
<!--    持久层-->
    <bean name="dao" class="com.spring.dao.impl.AccountDao">
        <property name="dataSource" ref="dataSource"/>
    </bean>
<!--    数据源-->
    <bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="username" value="root"/>
        <property name="password" value="adminadmin"/>
        <property name="url" value="jdbc:mysql://localhost:3306/spring_test"/>
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
    </bean>
<!--    配置事务管理器-->
    <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!-- 开启spring对注解事务的支持-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>

然后今天我们就只需要配置需要添加事务的类,这里专指业务层实现类AccountServiceImpl

package com.spring.service.impl;
import com.spring.service.IAccountService;
import com.spring.beans.Account;
import com.spring.dao.IAccountDao;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
/**
 * @author 28985
 */
@Transactional
public class AccountServiceImpl implements IAccountService {
    private IAccountDao accountDao;
    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }
    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    @Override
    public Account findAccountById(Integer id) {
        return accountDao.findById(id);
    }
    @Transactional(propagation = Propagation.REQUIRED,readOnly = false)
    @Override
    public void transfer(String sourceName, String targetName, float money) {
        System.out.println("转账");
        Account sourceAccount = accountDao.findByName(sourceName);
        Account targetAccount = accountDao.findByName(targetName);
        sourceAccount.setMoney(sourceAccount.getMoney()-money);
        targetAccount.setMoney(targetAccount.getMoney()+money);
        accountDao.update(sourceAccount);
//        int i= 1/0;
        accountDao.update(targetAccount);
    }
}

这时我们对比xml和注解两种配置方式

我们发现注解要针对每个方法做出不同的配置

而xml则不需要


相关实践学习
如何在云端创建MySQL数据库
开始实验后,系统会自动创建一台自建MySQL的 源数据库 ECS 实例和一台 目标数据库 RDS。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
6天前
|
安全 Java 数据库
一天十道Java面试题----第四天(线程池复用的原理------>spring事务的实现方式原理以及隔离级别)
这篇文章是关于Java面试题的笔记,涵盖了线程池复用原理、Spring框架基础、AOP和IOC概念、Bean生命周期和作用域、单例Bean的线程安全性、Spring中使用的设计模式、以及Spring事务的实现方式和隔离级别等知识点。
|
1天前
|
SQL XML Java
Spring5入门到实战------12、使用JdbcTemplate操作数据库(增删改查)。具体代码+讲解 【上篇】
这篇文章是Spring5框架的实战教程,详细讲解了如何使用JdbcTemplate进行数据库的增删改查操作,包括在项目中引入依赖、配置数据库连接池、创建实体类、定义DAO接口及其实现,并提供了具体的代码示例和测试结果,最后还提供了完整的XML配置文件和测试代码。
Spring5入门到实战------12、使用JdbcTemplate操作数据库(增删改查)。具体代码+讲解 【上篇】
|
4天前
|
SQL 数据库
Spring5入门到实战------13、使用JdbcTemplate操作数据库(批量增删改)。具体代码+讲解 【下篇】
这篇文章是Spring5框架的实战教程,深入讲解了如何使用JdbcTemplate进行数据库的批量操作,包括批量添加、批量修改和批量删除的具体代码实现和测试过程,并通过完整的项目案例展示了如何在实际开发中应用这些技术。
Spring5入门到实战------13、使用JdbcTemplate操作数据库(批量增删改)。具体代码+讲解 【下篇】
|
6天前
|
Java 程序员 数据库连接
女朋友不懂Spring事务原理,今天给她讲清楚了!
该文章讲述了如何解释Spring事务管理的基本原理,特别是针对女朋友在面试中遇到的问题。文章首先通过一个简单的例子引入了传统事务处理的方式,然后详细讨论了Spring事务管理的实现机制。
女朋友不懂Spring事务原理,今天给她讲清楚了!
|
4天前
|
XML Java 数据库
Spring5入门到实战------15、事务操作---概念--场景---声明式事务管理---事务参数--注解方式---xml方式
这篇文章是Spring5框架的实战教程,详细介绍了事务的概念、ACID特性、事务操作的场景,并通过实际的银行转账示例,演示了Spring框架中声明式事务管理的实现,包括使用注解和XML配置两种方式,以及如何配置事务参数来控制事务的行为。
Spring5入门到实战------15、事务操作---概念--场景---声明式事务管理---事务参数--注解方式---xml方式
|
4天前
|
XML 数据库 数据格式
Spring5入门到实战------14、完全注解开发形式 ----JdbcTemplate操作数据库(增删改查、批量增删改)。具体代码+讲解 【终结篇】
这篇文章是Spring5框架的实战教程的终结篇,介绍了如何使用注解而非XML配置文件来实现JdbcTemplate的数据库操作,包括增删改查和批量操作,通过创建配置类来注入数据库连接池和JdbcTemplate对象,并展示了完全注解开发形式的项目结构和代码实现。
Spring5入门到实战------14、完全注解开发形式 ----JdbcTemplate操作数据库(增删改查、批量增删改)。具体代码+讲解 【终结篇】
|
4天前
|
SQL XML Java
Spring5入门到实战------12、使用JdbcTemplate操作数据库(增删改查)。具体代码+讲解 【上篇】
这篇文章是Spring5框架的实战教程,详细讲解了如何使用JdbcTemplate进行数据库的增删改查操作,包括在项目中引入依赖、配置数据库连接池、创建实体类、定义DAO接口及其实现,并提供了具体的代码示例和测试结果,最后还提供了完整的XML配置文件和测试代码。
Spring5入门到实战------12、使用JdbcTemplate操作数据库(增删改查)。具体代码+讲解 【上篇】
|
6天前
|
前端开发 Java 数据库连接
一天十道Java面试题----第五天(spring的事务传播机制------>mybatis的优缺点)
这篇文章总结了Java面试中的十个问题,包括Spring事务传播机制、Spring事务失效条件、Bean自动装配方式、Spring、Spring MVC和Spring Boot的区别、Spring MVC的工作流程和主要组件、Spring Boot的自动配置原理和Starter概念、嵌入式服务器的使用原因,以及MyBatis的优缺点。
|
21天前
|
Java 测试技术 数据库
Spring Boot中的项目属性配置
本节课主要讲解了 Spring Boot 中如何在业务代码中读取相关配置,包括单一配置和多个配置项,在微服务中,这种情况非常常见,往往会有很多其他微服务需要调用,所以封装一个配置类来接收这些配置是个很好的处理方式。除此之外,例如数据库相关的连接参数等等,也可以放到一个配置类中,其他遇到类似的场景,都可以这么处理。最后介绍了开发环境和生产环境配置的快速切换方式,省去了项目部署时,诸多配置信息的修改。