20201126黄春跃

20201126黄春跃

知识点

Spring 中的 JdbcTemplate

JdbcTemplate 概述

它是 spring 框架中提供的一个对象,是对原始 Jdbc API 对象的简单封装。spring 框架为我们提供了很
多的操作模板类。
操作关系型数据的:
JdbcTemplate
HibernateTemplate
操作 nosql 数据库的:
RedisTemplate
操作消息队列的:
JmsTemplate
我们今天的主角在 spring-jdbc-5.0.2.RELEASE.jar 中,我们在导包的时候,除了要导入这个 jar 包
外,还需要导入一个 spring-tx-5.0.2.RELEASE.jar (它是和事务相关的)。

JdbcTemplate 对象的创建

public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
  public JdbcTemplate() {
}
  public JdbcTemplate(DataSource dataSource) {
setDataSource(dataSource);
afterPropertiesSet();
}
  public JdbcTemplate(DataSource dataSource, boolean lazyInit) {
    setDataSource(dataSource);
    setLazyInit(lazyInit);
    afterPropertiesSet();
 }
  public void setDataSource(@Nullable DataSource dataSource) {
this.dataSource = dataSource;
}
}

除了默认构造函数之外,都需要提供一个数据源。既然有setter方法,依据我们之前学过的依赖注入,
我们可以在配置文件中配置这些对象。

spring 中配置数据源

<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>

编写 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"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    https://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>

配置数据源

C3P0 、DBCP和Druid都可以。要想使用这些数据源都需要导入对应的 jar 包。

<!-- 数据源 -->
    <!-- C3P0 -->
    <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.2.1</version>
    </dependency>
    <!-- dbcp -->
    <!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -
->
    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.4</version>
    </dependency>
    <!-- DRUID -->
    <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.10</version>
    </dependency>

配置 C3P0 数据源

<!-- 配置DataSource对象 -->
  <bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="com.mysql.jdbc.Driver">
</property>
    <property name="jdbcUrl"
value="jdbc:mysql://localhost:3306/userinfo"></property>
    <property name="user" value="root"></property>
    <property name="password" value="root"></property>
  </bean>

配置 DBCP 数据源

<bean id="datasource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver">
</property>
    <property name="url" value="jdbc:mysql://localhost:3306/userinfo">
</property>
    <property name="username" value="root"></property>
    <property name="password" value="root"></property>
  </bean>

配置 spring 内置数据源

spring 框架也提供了一个内置数据源,我们也可以使用 spring 的内置数据源,它就在
spring-jdbc-5.0.2.REEASE.jar 包中:

<bean id="datasource" class="com.alibaba.druid.pool.DruidDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver">
</property>
    <property name="url" value="jdbc:mysql://localhost:3306/userinfo">
</property>
    <property name="username" value="root"></property>
    <property name="password" value="root"></property>
  </bean>

配置 Druid内置数据源

<bean id="datasource" class="com.alibaba.druid.pool.DruidDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver">
</property>
    <property name="url" value="jdbc:mysql://localhost:3306/userinfo">
</property>
    <property name="username" value="root"></property>
    <property name="password" value="root"></property>
  </bean>

将数据库连接的信息配置到属性文件中:

db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=

【引入外部的属性文件】

<!-- 引入外部属性文件: -->
  <!-- 第一种方式 -->
  <bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer
">
    <property name="location" value="classpath:db.properties"/>
  </bean>
  <!-- 第二种方式:需要引入context-->
  <context:property-placeholder location="classpath:db.properties"/>

JdbcTemplate 的增删改查操作

前期准备

数据库表还是使用 userinfo.tb_account

在 spring 配置文件中配置 JdbcTemplate
<?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"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
    https://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">
  <context:property-placeholder location="classpath:db.properties"/>
  <!-- 配置一个数据库的操作模板:JdbcTemplate -->
  <bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="datasource"></property>
  </bean>
  <bean id="datasource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${jdbc.driver}"></property>
    <property name="url" value="${jdbc.url}"></property>
    <property name="username" value="${jdbc.username}"></property>
    <property name="password" value="${jdbc.password}"></property>
  </bean>
</beans>
各种操作的测试方法

在 dao 中使用 JdbcTemplate

创建实体类
package com.itlaobing.spring.dao;

import com.itlaobing.spring.model.Account;

public interface IAccountDao {
    //通过id查找
    public Account findAccountById(Integer id);
    //通过name查找
    public Account findAccountByName(String name);
    //更新账户
    public void updateAccount(Account account);

}

第一种方式:在 dao 中定义 JdbcTemplate
package com.itlaobing.spring.dao.impl;

import com.itlaobing.spring.dao.IAccountDao;
import com.itlaobing.spring.model.Account;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
@Repository
public class AccountDaoImpl implements IAccountDao {
    //定义 JdbcTemplate
    @Resource
    private JdbcTemplate jdbcTemplate;
    //jdbcTemplate的set方法

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

    @Override
    public Account findAccountById(Integer id) {
        List<Account> list = jdbcTemplate.query("select * from tb_account where id = ?" ,new AccountRowMapper(),id);
        return list.isEmpty()?null:list.get(0);
    }

    @Override
    public Account findAccountByName(String name) {
        List<Account> list = jdbcTemplate.query("select * from tb_account where name = ?" ,new AccountRowMapper(),name);
        if(list.isEmpty()){
          return null;
       }
        if(list.size()>1){
          throw new RuntimeException("结果集不唯一,不是只有一个账户对象");
       }
        return list.get(0);
        }

    @Override
    public void updateAccount(Account account) {
        jdbcTemplate.update("update tb_account set money = ? where id = ?",account.getMoney(),account.getId());
    }
}
class AccountRowMapper implements RowMapper<Account>{

    @Override
    public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
        Account account = new Account();
        account.setId(rs.getInt("id"));
        account.setName(rs.getString("name"));
        account.setMoney(rs.getFloat("money"));
        return account;
    }
}

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"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
    https://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">
  <context:property-placeholder location="classpath:db.properties"/>
  <!-- 配置一个 dao -->
  <bean id="accountDao" class="com.itlaobing.dao.impl.AccountDaoImpl">
    <!-- 注入 jdbcTemplate -->
    <property name="jdbcTemplate" ref="jdbcTemplate"></property>
  </bean>
  <!-- 配置一个数据库的操作模板:JdbcTemplate -->
  <bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="datasource"></property>
  </bean>
  <bean id="datasource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${jdbc.driver}"></property>
    <property name="url" value="${jdbc.url}"></property>
    <property name="username" value="${jdbc.username}"></property>
    <property name="password" value="${jdbc.password}"></property>
  </bean>
</beans>

测试

package com.itlaobing.dao.impl;
import com.itlaobing.dao.IAccountDao;
import com.itlaobing.model.Account;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
/**
* @Classname AccountDaoImplTest
* @Description TODO()
* @Date 2019/12/17 20:45
* @Author by Administrator
* @Version v1.0
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring.xml")
public class AccountDaoImplTest {
  @Resource
  private IAccountDao accountDao;
  @Test
  public void findAccountById() {
    System.out.println(accountDao.findAccountById(1));
 }
  @Test
  public void findAccountByName() {
    System.out.println(accountDao.findAccountByName("aaa"));
 }
  @Test
  public void updateAccount() {
    Account account = new Account();
    account.setId(1);
    account.setMoney(100000f);
    accountDao.updateAccount(account);
 }
}
第二种方式:让 dao 继承 JdbcDaoSupport
package com.itlaobing.spring.dao.impl;

import com.itlaobing.spring.dao.IAccountDao;
import com.itlaobing.spring.model.Account;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class AccountDaoImpl2 extends JdbcDaoSupport implements IAccountDao {
//    //定义 JdbcTemplate
//    private JdbcTemplate jdbcTemplate;
//    //jdbcTemplate的set方法
//
//    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
//        this.jdbcTemplate = jdbcTemplate;
//    }

    @Override
    public Account findAccountById(Integer id) {
        List<Account> list = getJdbcTemplate().query("select * from tb_account where id = ?" ,new AccountRowMapper(),id);
        return list.isEmpty()?null:list.get(0);
    }

    @Override
    public Account findAccountByName(String name) {
        List<Account> list = getJdbcTemplate().query("select * from tb_account where name = ?" ,new AccountRowMapper(),name);
        if(list.isEmpty()){
            return null;
        }
        if(list.size()>1){
            throw new RuntimeException("结果集不唯一,不是只有一个账户对象");
        }
        return list.get(0);
    }

    @Override
    public void updateAccount(Account account) {
        getJdbcTemplate().update("update tb_account set money = ? where id = ?",account.getMoney(),account.getId());
    }
}
class AccountRowMapper2 implements RowMapper<Account>{

    @Override
    public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
        Account account = new Account();
        account.setId(rs.getInt("id"));
        account.setName(rs.getString("name"));
        account.setMoney(rs.getFloat("money"));
        return account;
    }
}

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"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
    https://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">
  <context:property-placeholder location="classpath:db.properties"/>
  <!-- 配置 dao2 -->
  <bean id="accountDao2" class="com.itlaobing.dao.impl.AccountDaoImpl2">
    <!-- 注入 dataSource -->
    <property name="dataSource" ref="datasource"></property>
  </bean>
  <!-- 配置一个数据库的操作模板:JdbcTemplate -->
  <bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="datasource"></property>
  </bean>
  <bean id="datasource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${jdbc.driver}"></property>
    <property name="url" value="${jdbc.url}"></property>
    <property name="username" value="${jdbc.username}"></property>
    <property name="password" value="${jdbc.password}"></property>
  </bean>
</beans>

Spring 中的事务控制

第一:JavaEE 体系进行分层开发,事务处理位于业务层,Spring 提供了分层设计业务层的事务处理解
决方案。
第二:spring 框架为我们提供了一组事务控制的接口。具体在后面会介绍。这组接口是在 spring-tx-
5.0.2.RELEASE.jar 中。
第三:spring 的事务控制都是基于 AOP 的,它既可以使用编程的方式实现,也可以使用配置的方式实
现。我们学习的重点是使用配置的方式实现。

Spring 中事务控制的 API 介绍

PlatformTransactionManager

此接口是 spring 的事务管理器,它里面提供了我们常用的操作事务的方法

基于 XML 的声明式事务控制(配置方式)

第一步:拷贝必要的 jar 包(pom.xml)
<properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <maven.compiler.source>1.8</maven.compiler.source>
  <maven.compiler.target>1.8</maven.compiler.target>
  <spring.version>5.0.2.RELEASE</spring.version>
 </properties>
 <dependencies>
  <dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>4.12</version>
   <scope>test</scope>
  </dependency>
  <!-- https://mvnrepository.com/artifact/org.springframework/spring-
context -->
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <!-- https://mvnrepository.com/artifact/org.springframework/spring-
jdbc -->
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-jdbc</artifactId>
   <version>${spring.version}</version>
  </dependency>
  
   <!-- https://mvnrepository.com/artifact/org.springframework/spring-
aspects -->
   <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-aspects</artifactId>
     <version>5.0.2.RELEASE</version>
   </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-test</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.47</version>
  </dependency>
  <!-- 日志 -->
  <dependency>
   <groupId>log4j</groupId>
   <artifactId>log4j</artifactId>
    <version>1.2.12</version>
  </dependency>
  <dependency>
   <groupId>org.projectlombok</groupId>
   <artifactId>lombok</artifactId>
   <version>1.18.8</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"
   xmlns:context="http://www.springframework.org/schema/context"
  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">
</beans>
第三步:准备数据库表和实体类
Data
public class Account implements Serializable {
  private Integer id;
  private String name;
  private Float money;
}
第四步:编写业务层接口和实现类
package com.itlaobing.spring.service.impl;

import com.itlaobing.spring.dao.IAccountDao;
import com.itlaobing.spring.model.Account;
import com.itlaobing.spring.service.IAccountService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class AccountServiceImpl implements IAccountService {
    @Resource
    private IAccountDao accountDao;

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

    @Override
    public Account findAccountById(Integer id) {
        return null;
    }

    @Override
    @Transactional(readOnly=false,propagation=Propagation.REQUIRED)
    public void transfer(String sourceName, String targeName, Float money) {
        //1.根据名称查询两个账户
        Account source = accountDao.findAccountByName(sourceName);
        Account target = accountDao.findAccountByName(targeName);
        //2.修改两个账户的金额
        source.setMoney(source.getMoney()-money);//转出账户减钱
        target.setMoney(target.getMoney()+money);//转入账户加钱
        //3.更新两个账户
        accountDao.updateAccount(source);
//        int i=1/0;
        accountDao.updateAccount(target);
        }
}

第五步:编写 Dao 接口和实现类
package com.itlaobing.spring.dao;

import com.itlaobing.spring.model.Account;

public interface IAccountDao {
    //通过id查找
    public Account findAccountById(Integer id);
    //通过name查找
    public Account findAccountByName(String name);
    //更新账户
    public void updateAccount(Account account);

}

package com.itlaobing.dao.impl;
import com.itlaobing.dao.IAccountDao;
import com.itlaobing.mapper.AccountRowMapper;
import com.itlaobing.model.Account;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import java.util.List;
/**
* @Classname AccountDaoImpl
* @Description TODO()
* @Date 2019/12/17 20:41
* @Author by Administrator
* @Version v1.0
*/
public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {
  @Override
  public Account findAccountById(Integer id) {
    List<Account> list = getJdbcTemplate().query("select * from
tb_account where id = ?"
       ,new AccountRowMapper(),id);
    return list.isEmpty()?null:list.get(0);
 }
  @Override
  public Account findAccountByName(String name) {
    List<Account> list = getJdbcTemplate().query("select * from
tb_account where name= ? "
       ,new AccountRowMapper(),name);
    if(list.isEmpty()){
      return null;
   }
    if(list.size()>1){
      throw new RuntimeException("结果集不唯一,不是只有一个账户对象");
   }
    return list.get(0);
 }
  @Override
  public void updateAccount(Account account) {
    getJdbcTemplate().update("update tb_account set money = ? where id
= ?"
       ,account.getMoney(),account.getId());
 }
}

第六步:在配置文件中配置业务层和持久层

<?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"
       xmlns:context="http://www.springframework.org/schema/context"
       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">
    <!-- 引入外部属性文件:db.properties -->
    <context:property-placeholder location="db.properties"/>

    <context:component-scan base-package="com.itlaobing"/>

    <!-- 事务的配置 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*" read-only="false" propagation="REQUIRED"/>
            <tx:method name="find*" read-only="true" propagation="SUPPORTS"></tx:method>
        </tx:attributes>
    </tx:advice>
    <tx:annotation-driven transaction-manager="transactionManager"/>

    <!-- 配置 aop -->
      <aop:config>
        <!-- 配置切入点表达式 -->
        <aop:pointcut expression="execution(* com.itlaobing.spring.service.impl.*.*(..))" id="pt1"/>
          <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
      </aop:config>
    <!-- 配置一个数据库的操作模板:JdbcTemplate -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="datasource"></property>
    </bean>

    <!-- 配置 Druid内置数据源 -->
    <bean id="datasource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url"
                  value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=utf8"></property>
        <property name="username" value="root"></property>
        <property name="password" value=""></property>
    </bean>

    <!-- 配置一个service-->
    <bean id="accountService" class="com.itlaobing.spring.service.impl.AccountServiceImpl">
        <!-- 注入 accountDao-->
        <property name="accountDao" ref="accountDao"></property>
    </bean>

    <!-- 配置一个事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="datasource"></property>
    </bean>

    <!-- 配置一个dao-->
    <bean id="accountDao" class="com.itlaobing.spring.dao.impl.AccountDaoImpl">
        <!-- 注入 jdbcTemplate-->
        <property name="jdbcTemplate" ref="jdbcTemplate"></property>
    </bean>

    <!-- 配置一个dao2-->
    <bean id="accountDao2" class="com.itlaobing.spring.dao.impl.AccountDaoImpl2">
        <!-- 注入 jdbcTemplate-->
        <property name="dataSource" ref="datasource"></property>
    </bean>

</beans>

测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring.xml")
public class AccountServiceImplTest {
  @Resource
  private IAccountService accountService;
  @Test
  public void transfer() {
    accountService.transfer("aaa", "bbb",100f);
 }
}

基于注解的配置方式

步骤和之前类似,照着文档即可。

配置类

package com.itlaobing.spring.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * @Classname SpringConfig
 * @Description TODO()
 * @Date 2020/11/26 0026 9:54
 * @Author by Administrator
 * @Version v1.0
 */
// 这个类是 spring 配置类
@Configuration
@ComponentScan("com.itlaobing.spring")
// 读取 db 配置文件
@PropertySource("db.properties")
@EnableTransactionManagement
public class SpringConfig {

    @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("jdbcTemplate")
    @Scope("prototype")
    public JdbcTemplate getJdbcTemplate(DataSource dataSource)
     {
        return new JdbcTemplate(dataSource);
    }


    @Bean("dataSource")
    public DataSource getDataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }
    @Bean("transactionManager")
    public DataSourceTransactionManager getDataSourceTransactionManager(){
        return new DataSourceTransactionManager(getDataSource());
    }

}

标签

评论

© 2021 成都云创动力科技有限公司 蜀ICP备20006351号-1