• Spring事务管理与模板对象


    1.事务管理

    1.事务回顾

    事务指数据库中多个操作合并在一起形成的操作序列

    事务的作用

    数据库操作序列中个别操作失败时,提供一种方式使数据库状态恢复到正常状态(A),保障数据库即使在异常状态下仍能保持数据一致性C)(要么操作前状态,要么操作后状态)。

    当出现并发访问数据库时,在多个访问间进行相互隔离,防止并发访问操作结果互相干扰(I

    事务的特征(ACID)

    原子性(Atomicity)指事务是一个不可分割的整体,其中的操作要么全执行或全不执行

    一致性(Consistency)事务前后数据的完整性必须保持一致

    隔离性(Isolation)事务的隔离性是多个用户并发访问数据库时,数据库为每一个用户开启的事务,不能被其他事务的操作数据所干扰,多个并发事务之间要相互隔离

    持久性(Durability)持久性是指一个事务一旦被提交,它对数据库中数据的改变就是永久性的,接下来即使数据库发生故障也不应该对其有任何影响

    事务的隔离级

    脏读:允许读取未提交的信息

    原因:Read uncommitted

    解决方案: (表级读锁)

    不可重复读:读取过程中单个数据发生了变化

    解决方案: Repeatable read (行级写锁)

    幻读:读取过程中数据条目发生了变化

    解决方案: Serializable(表级写锁)

    2.Spring事务核心对象

    J2EE开发使用分层设计的思想进行,对于简单的业务层转调数据层的单一操作,事务开启在业务层或者数据层并无太大差别,当业务中包含多个数据层的调用时,需要在业务层开启事务,对数据层中多个操作进行组合并归属于同一个事务进行处理

    Spring为业务层提供了整套的事务解决方案

            PlatformTransactionManager

            TransactionDefinition

            TransactionStatus

    PlatformTransactionManager(平台事务管理器)

    这是一个接口

    平台事务管理器实现类:

    DataSourceTransactionManager   适用于Spring JDBC或MyBatis

    HibernateTransactionManager   适用于Hibernate3.0及以上版本

    JpaTransactionManager   适用于JPA

    JdoTransactionManager   适用于JDO

    JtaTransactionManager   适用于JTA

    JPA(Java Persistence API)Java EE 标准之一,为POJO提供持久化标准规范,并规范了持久化开发的统一API,符合JPA规范的开发可以在不同的JPA框架下运行

    JDO(Java Data Object )是Java对象持久化规范,用于存取某种数据库中的对象,并提供标准化API。与JDBC相比,JDBC仅针对关系数据库进行操作,JDO可以扩展到关系数据库、文件、XML、对象数据库(ODBMS)等,可移植性更强

    JTA(Java Transaction API)Java EE 标准之一,允许应用程序执行分布式事务处理。与JDBC相比,JDBC事务则被限定在一个单一的数据库连接,而一个JTA事务可以有多个参与者,比如JDBC连接、JDO 都可以参与到一个JTA事务中

    此接口定义了事务的基本操作

    获取事务

    TransactionStatus getTransaction(TransactionDefinition definition)
    

    提交事务 

    void commit(TransactionStatus status) 
    

    回滚事务 

    void rollback(TransactionStatus status)
    

    TransactionDefinition(事务定义的接口)

    此接口定义了事务的基本信息

    获取事务定义名称

    String getName()
    

    获取事务的读写属性

    boolean isReadOnly()

    获取事务隔离级别

    int getIsolationLevel()

    获事务超时时间

    int getTimeout()

    获取事务传播行为特征

    int getPropagationBehavior()

    TransactionStatus(事务状态的接口)

    此接口定义了事务在执行过程中某个时间点上的状态信息及对应的状态操作

    获取事务是否处于新开启事务状态

    boolean isNewTransaction()

    获取事务是否处于已完成状态

    boolean isCompleted()

    获取事务是否处于回滚状态

    boolean isRolbackOnly()

    刷新事务状态

    void flush()

    获取事务是否具有回滚存储点

    boolean hasSavepoint()

    设置事务处于回滚状态

    void setRollbackOnly()

    3.事务控制方式

    编程式

    声明式(XML)

    声明式(注解)

    4.案例环境

    银行转账业务说明

    银行转账操作中,涉及从A账户到B账户的资金转移操作。数据层仅提供单条数据的基础操作,未设计多账户间的业务操作

    1. package com.dao;
    2. import org.apache.ibatis.annotations.Param;
    3. public interface AccountDao {
    4. /*
    5. * 入账操作
    6. * name 入账用户名
    7. * money 入账金额
    8. */
    9. void inMoney(@Param("name") String name, @Param("money") Double money);
    10. /*
    11. * 入账操作
    12. * name 出账用户名
    13. * money 出账金额
    14. */
    15. void outMoney(@Param("name") String name, @Param("money") Double money);
    16. }
    1. package com.domain;
    2. public class Account {
    3. private Integer id;
    4. private String name;
    5. private Double money;
    6. public Integer getId() {
    7. return id;
    8. }
    9. public void setId(Integer id) {
    10. this.id = id;
    11. }
    12. public String getName() {
    13. return name;
    14. }
    15. public void setName(String name) {
    16. this.name = name;
    17. }
    18. public Double getMoney() {
    19. return money;
    20. }
    21. public void setMoney(Double money) {
    22. this.money = money;
    23. }
    24. @Override
    25. public String toString() {
    26. return "Account{" +
    27. "id=" + id +
    28. ", name='" + name + '\'' +
    29. ", money=" + money +
    30. '}';
    31. }
    32. }
    1. package com.service;
    2. public interface AccountService {
    3. /*
    4. * 转账操作
    5. * outName 出账用户名
    6. * inName 入账用户名
    7. * money 转账金额
    8. */
    9. public void transfer(String outName, String inName, Double money);
    10. }
    1. package com.service.impl;
    2. import com.dao.AccountDao;
    3. import com.service.AccountService;
    4. public class AccountServiceImpl implements AccountService {
    5. private AccountDao accountDao;
    6. public void setAccountDao(AccountDao accountDao) {
    7. this.accountDao = accountDao;
    8. }
    9. @Override
    10. public void transfer(String outName, String inName, Double money) {
    11. accountDao.inMoney(outName,money);
    12. accountDao.outMoney(inName,money);
    13. }
    14. }

    1. "1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xmlns:context="http://www.springframework.org/schema/context"
    5. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    6. <context:property-placeholder location="classpath:*.properties"/>
    7. <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    8. <property name="driverClassName" value="${jdbc.driver}"/>
    9. <property name="url" value="${jdbc.url}"/>
    10. <property name="username" value="${jdbc.username}"/>
    11. <property name="password" value="${jdbc.password}"/>
    12. bean>
    13. <bean id="accountService" class="com.service.impl.AccountServiceImpl">
    14. <property name="accountDao" ref="accountDao"/>
    15. bean>
    16. <bean class="org.mybatis.spring.SqlSessionFactoryBean">
    17. <property name="dataSource" ref="dataSource"/>
    18. <property name="typeAliasesPackage" value="com.domain"/>
    19. bean>
    20. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    21. <property name="basePackage" value="com.dao"/>
    22. bean>
    23. beans>
    1. "1.0" encoding="UTF-8" ?>
    2. mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    3. <mapper namespace="com.dao.AccountDao">
    4. <update id="inMoney">
    5. update account set money = money + #{money} where name = #{name}
    6. update>
    7. <update id="outMoney">
    8. update account set money = money - #{money} where name = #{name}
    9. update>
    10. mapper>
    1. jdbc.driver=com.mysql.cj.jdbc.Driver
    2. jdbc.url=jdbc:mysql://localhost:3306/spring_db?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8&useSSL=false
    3. jdbc.username=root
    4. jdbc.password=123456

    5.使用AOP控制事务 (XML)

    将业务层的事务处理功能抽取出来制作成AOP通知,利用环绕通知运行期动态织入

    范例

    1. public Object tx(ProceedingJoinPoint pjp) throws Throwable {
    2. DataSourceTransactionManager dstm = new DataSourceTransactionManager();
    3. dstm.setDataSource(dataSource);
    4. TransactionDefinition td = new DefaultTransactionDefinition();
    5. TransactionStatus ts = dstm.getTransaction(td);
    6. Object ret = pjp.proceed(pjp.getArgs());
    7. dstm.commit(ts);
    8. return ret;
    9. }
    1. <bean id="txAdvice" class="com.aop.TxAdvice">
    2. <property name="dataSource" ref="dataSource"/>
    3. bean>

    使用aop:advisor在AOP配置中引用事务专属通知类

    1. <aop:config>
    2. <aop:pointcut id="pt" expression="execution(* *..transfer(..))"/>
    3. <aop:aspect ref="txAdvice">
    4. <aop:around method="tx" pointcut-ref="pt"/>
    5. aop:aspect>
    6. aop:config>

    样例

    1. package com.service.impl;
    2. import com.dao.AccountDao;
    3. import com.service.AccountService;
    4. import javafx.application.Platform;
    5. import org.springframework.jdbc.datasource.DataSourceTransactionManager;
    6. import org.springframework.transaction.PlatformTransactionManager;
    7. import org.springframework.transaction.TransactionDefinition;
    8. import org.springframework.transaction.TransactionStatus;
    9. import org.springframework.transaction.support.DefaultTransactionDefinition;
    10. import javax.sql.DataSource;
    11. public class AccountServiceImpl implements AccountService {
    12. private AccountDao accountDao;
    13. public void setAccountDao(AccountDao accountDao) {
    14. this.accountDao = accountDao;
    15. }
    16. /*private DataSource dataSource;
    17. public void setDataSource(DataSource dataSource) {
    18. this.dataSource = dataSource;
    19. }*/
    20. @Override
    21. public void transfer(String outName, String inName, Double money) {
    22. /* //开启事务
    23. PlatformTransactionManager ptm = new DataSourceTransactionManager(dataSource);
    24. //事务定义
    25. TransactionDefinition td = new DefaultTransactionDefinition();
    26. //事务状态
    27. TransactionStatus ts = ptm.getTransaction(td);*/
    28. accountDao.inMoney(outName,money);
    29. //int i = 1/0;
    30. accountDao.outMoney(inName,money);
    31. /*ptm.commit(ts);*/
    32. }
    33. }

    1. package com.aop;
    2. import org.aspectj.lang.ProceedingJoinPoint;
    3. import org.springframework.jdbc.datasource.DataSourceTransactionManager;
    4. import org.springframework.transaction.PlatformTransactionManager;
    5. import org.springframework.transaction.TransactionDefinition;
    6. import org.springframework.transaction.TransactionStatus;
    7. import org.springframework.transaction.support.DefaultTransactionDefinition;
    8. import javax.sql.DataSource;
    9. public class TxAdvice {
    10. private DataSource dataSource;
    11. public void setDataSource(DataSource dataSource) {
    12. this.dataSource = dataSource;
    13. }
    14. public Object transactionManager(ProceedingJoinPoint pjp) throws Throwable{
    15. //开启事务
    16. PlatformTransactionManager ptm = new DataSourceTransactionManager(dataSource);
    17. //事务定义
    18. TransactionDefinition td = new DefaultTransactionDefinition();
    19. //事务状态
    20. TransactionStatus ts = ptm.getTransaction(td);
    21. Object ret = pjp.proceed(pjp.getArgs());
    22. ptm.commit(ts);
    23. return ret;
    24. }
    25. }
    1. <bean id="txAdvice" class="com.aop.TxAdvice">
    2. <property name="dataSource" ref="dataSource"/>
    3. bean>
    4. <aop:config>
    5. <aop:pointcut id="pt" expression="execution(* *..taransfer(..))"/>
    6. <aop:aspect ref="txAdvice">
    7. <aop:around method="transactionManager" pointcut-ref="pt"/>
    8. aop:aspect>
    9. aop:config>

    6.声明式事务(XML)

    tx配置----tx:advice

    名称:tx:advice

    类型:标签

    归属:beans标签

    作用:专用于声明事务通知

    格式

    1. <beans>
    2. <tx:advice id="txAdvice" transaction-manager="txManager">
    3. tx:advice>
    4. beans>

    基本属性:

    id :用于配置aop时指定通知器的id

    transaction-manager :指定事务管理器bean

    tx配置----tx:attributes

    名称:tx:attributes

    类型:标签

    归属:tx:advice标签

    作用:定义通知属性

    格式

    1. <tx:advice id="txAdvice" transaction-manager="txManager">
    2. <tx:attributes>
    3. tx:attributes>
    4. tx:advice>

    基本属性:无

    tx配置----tx:method

    名称:tx:method

    类型:标签

    归属:tx:attribute标签

    作用:设置具体的事务属性

    格式

    1. <tx:attributes>
    2. <tx:method name="*" read-only="false" />
    3. <tx:method name="get*" read-only="true" />
    4. tx:attributes>

    说明:通常事务属性会配置多个,包含一个读写的全事务属性,一个只读的查询类事务属性 

    样例

    开启tx命名空间 

    1. <beans xmlns="http://www.springframework.org/schema/beans"
    2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xmlns:context="http://www.springframework.org/schema/context"
    4. xmlns:aop="http://www.springframework.org/schema/aop"
    5. xmlns:tx="http://www.springframework.org/schema/tx"
    6. xsi:schemaLocation="http://www.springframework.org/schema/beans
    7. http://www.springframework.org/schema/beans/spring-beans.xsd
    8. http://www.springframework.org/schema/context
    9. https://www.springframework.org/schema/context/spring-context.xsd
    10. http://www.springframework.org/schema/tx
    11. https://www.springframework.org/schema/tx/spring-tx.xsd
    12. http://www.springframework.org/schema/aop
    13. https://www.springframework.org/schema/aop/spring-aop.xsd">
    1. <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    2. <property name="dataSource" ref="dataSource"/>
    3. bean>
    4. <tx:advice id="txAdvice" transaction-manager="txManager">
    5. <tx:attributes>
    6. <tx:method name="*" read-only="false"/>
    7. <tx:method name="get*" read-only="true"/>
    8. <tx:method name="find" read-only="true"/>
    9. <tx:method name="transfer" read-only="false"/>
    10. tx:attributes>
    11. tx:advice>
    12. <aop:config>
    13. <aop:pointcut id="pt" expression="execution(* com.service.*Service.*(..))"/>
    14. <aop:advisor advice-ref="txAdvice" pointcut-ref="pt"/>
    15. aop:config>

     此时aop.TxAdvice就可以删除了

    此段也要删除

    aop:advice与aop:advisor区别

    aop:advice配置的通知类可以是普通java对象,不实现接口,也不使用继承关系

    aop:advisor配置的通知类必须实现通知接口

            MethodBeforeAdvice

            AfterReturningAdvice

            ThrowsAdvice

            ……

    7.tx:method属性

    1. <tx:method
    2. name="*" 待添加事务的方法名表达式(支持*号通配符)
    3. read-only="false" 设置事务的读写属性true为只读false为读写
    4. timeout="-1" 设置事务超时时长单位秒
    5. isolation="DEFAULT" 设置事务隔离级别该隔离级别设定是基于Spring的设定非数据库端
    6. no-rollback-for="java.lang.ArithmeticException" 设置事务中不回滚的异常多个异常间使用,分割
    7. rollback-for="" 设置事务中必回滚的异常多个异常间使用,分割
    8. propagation="REQUIRED" 设置事务的传播行为
    9. />

    8.事务传播行为 

    事务传播行为描述的是事务协调员对事务管理员所携带事务的处理态度

    企业开发过程中,发现同属于同一个事务控制的各个业务中,如果某个业务与其他业务隔离度较高,拥有差异化的数据业务控制情况,通常使用事务传播行为对其进行控制

    9.声明式事务(注解)

    @Transactional

    名称:@Transactional

    类型:方法注解,类注解,接口注解

    位置:方法定义上方,类定义上方,接口定义上方

    作用:设置当前类/接口中所有方法或具体方法开启事务,并指定相关事务属性

    范例

    1. @Transactional(
    2. readOnly = false,
    3. timeout = -1,
    4. isolation = Isolation.DEFAULT,
    5. rollbackFor = {ArithmeticException.class, IOException.class},
    6. noRollbackFor = {},
    7. propagation = Propagation.REQUIRES_NEW
    8. )

    tx:annotation-driven

    名称:tx:annotation-driven

    类型:标签

    归属:beans标签

    作用:开启事务注解驱动,并指定对应的事务管理器

    范例

    <tx:annotation-driven transaction-manager="txManager"/>
    

    样例

    1. "1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xmlns:context="http://www.springframework.org/schema/context"
    5. xmlns:aop="http://www.springframework.org/schema/aop"
    6. xmlns:tx="http://www.springframework.org/schema/tx"
    7. xsi:schemaLocation="http://www.springframework.org/schema/beans
    8. http://www.springframework.org/schema/beans/spring-beans.xsd
    9. http://www.springframework.org/schema/context
    10. https://www.springframework.org/schema/context/spring-context.xsd
    11. http://www.springframework.org/schema/tx
    12. https://www.springframework.org/schema/tx/spring-tx.xsd
    13. http://www.springframework.org/schema/aop
    14. https://www.springframework.org/schema/aop/spring-aop.xsd">
    15. <context:property-placeholder location="classpath:*.properties"/>
    16. <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    17. <property name="driverClassName" value="${jdbc.driver}"/>
    18. <property name="url" value="${jdbc.url}"/>
    19. <property name="username" value="${jdbc.username}"/>
    20. <property name="password" value="${jdbc.password}"/>
    21. bean>
    22. <bean id="accountService" class="com.service.impl.AccountServiceImpl">
    23. <property name="accountDao" ref="accountDao"/>
    24. bean>
    25. <bean class="org.mybatis.spring.SqlSessionFactoryBean">
    26. <property name="dataSource" ref="dataSource"/>
    27. <property name="typeAliasesPackage" value="com.domain"/>
    28. bean>
    29. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    30. <property name="basePackage" value="com.dao"/>
    31. bean>
    32. <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    33. <property name="dataSource" ref="dataSource"/>
    34. bean>
    35. <tx:annotation-driven transaction-manager="txManager"/>
    36. beans>

    1. package com.service;
    2. import org.springframework.transaction.annotation.Isolation;
    3. import org.springframework.transaction.annotation.Propagation;
    4. import org.springframework.transaction.annotation.Transactional;
    5. @Transactional(isolation = Isolation.DEFAULT)
    6. public interface AccountService {
    7. /*
    8. * 转账操作
    9. * outName 出账用户名
    10. * inName 入账用户名
    11. * money 转账金额
    12. */
    13. @Transactional(
    14. readOnly = false,
    15. timeout = -1,
    16. isolation = Isolation.DEFAULT,
    17. rollbackFor = {}, //java.lang.ArithmeticException.class, IOException.class
    18. noRollbackFor = {},
    19. propagation = Propagation.REQUIRED
    20. )
    21. public void transfer(String outName, String inName, Double money);
    22. }

    10.声明式事务(纯注解驱动)

    名称:@EnableTransactionManagement

    类型:类注解

    位置:Spring注解配置类上方

    作用:开启注解驱动,等同XML格式中的注解驱动

    范例

    1. @Configuration
    2. @ComponentScan("com.lichee")
    3. @PropertySource("classpath:jdbc.properties")
    4. @Import({JDBCConfig.class,MyBatisConfig.class,TransactionManagerConfig.class})
    5. @EnableTransactionManagement
    6. public class SpringConfig {
    7. }
    1. public class TransactionManagerConfig {
    2. @Bean
    3. public PlatformTransactionManager getTransactionManager(@Autowired DataSource dataSource){
    4. return new DataSourceTransactionManager(dataSource);
    5. }
    6. }

    样例

    1. package com.domain;
    2. public class Account {
    3. private Integer id;
    4. private String name;
    5. private Double money;
    6. public Integer getId() {
    7. return id;
    8. }
    9. public void setId(Integer id) {
    10. this.id = id;
    11. }
    12. public String getName() {
    13. return name;
    14. }
    15. public void setName(String name) {
    16. this.name = name;
    17. }
    18. public Double getMoney() {
    19. return money;
    20. }
    21. public void setMoney(Double money) {
    22. this.money = money;
    23. }
    24. @Override
    25. public String toString() {
    26. return "Account{" +
    27. "id=" + id +
    28. ", name='" + name + '\'' +
    29. ", money=" + money +
    30. '}';
    31. }
    32. }
    1. package com.dao;
    2. import org.apache.ibatis.annotations.Param;
    3. import org.apache.ibatis.annotations.Update;
    4. public interface AccountDao {
    5. @Update("update account set money = money + #{money} where name = #{name}")
    6. void inMoney(@Param("name") String name, @Param("money") Double money);
    7. @Update("update account set money = money - #{money} where name = #{name}")
    8. void outMoney(@Param("name") String name, @Param("money") Double money);
    9. }
    1. package com.service;
    2. import org.springframework.transaction.annotation.Transactional;
    3. @Transactional
    4. public interface AccountService {
    5. public void transfer(String outName, String inName, Double money);
    6. }
    1. package com.service.impl;
    2. import com.dao.AccountDao;
    3. import com.service.AccountService;
    4. import org.apache.ibatis.annotations.Arg;
    5. import org.springframework.beans.factory.annotation.Autowired;
    6. import org.springframework.stereotype.Service;
    7. import org.springframework.transaction.annotation.Isolation;
    8. import org.springframework.transaction.annotation.Propagation;
    9. import org.springframework.transaction.annotation.Transactional;
    10. import java.io.IOException;
    11. @Service("accountService")
    12. public class AccountServiceImpl implements AccountService {
    13. @Autowired
    14. private AccountDao accountDao;
    15. public void transfer(String outName, String inName, Double money) {
    16. accountDao.inMoney(outName,money);
    17. //int i = 1/0;
    18. accountDao.outMoney(inName,money);
    19. }
    20. }
    1. package com.config;
    2. import org.springframework.context.annotation.*;
    3. import org.springframework.transaction.annotation.EnableTransactionManagement;
    4. @Configuration
    5. @ComponentScan("com")
    6. @PropertySource("classpath:jdbc.properties")
    7. @Import({JDBCConfig.class,MyBatisConfig.class})
    8. @EnableTransactionManagement
    9. public class SpringConfig {
    10. }
    1. package com.config;
    2. import com.alibaba.druid.pool.DruidDataSource;
    3. import org.springframework.beans.factory.annotation.Value;
    4. import org.springframework.context.annotation.Bean;
    5. import org.springframework.jdbc.datasource.DataSourceTransactionManager;
    6. import org.springframework.transaction.PlatformTransactionManager;
    7. import javax.sql.DataSource;
    8. public class JDBCConfig {
    9. @Value("${jdbc.driver}")
    10. private String driver;
    11. @Value("${jdbc.url}")
    12. private String url;
    13. @Value("${jdbc.username}")
    14. private String userName;
    15. @Value("${jdbc.password}")
    16. private String password;
    17. @Bean("dataSource")
    18. public DataSource getDataSource(){
    19. DruidDataSource ds = new DruidDataSource();
    20. ds.setDriverClassName(driver);
    21. ds.setUrl(url);
    22. ds.setUsername(userName);
    23. ds.setPassword(password);
    24. return ds;
    25. }
    26. public PlatformTransactionManager gerTransactionManager(DataSource dataSource){
    27. return new DataSourceTransactionManager(dataSource);
    28. }
    29. }
    1. package com.config;
    2. import org.mybatis.spring.SqlSessionFactoryBean;
    3. import org.mybatis.spring.mapper.MapperScannerConfigurer;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.context.annotation.Bean;
    6. import javax.sql.DataSource;
    7. public class MyBatisConfig {
    8. @Bean
    9. public SqlSessionFactoryBean getSqlSessionFactoryBean(@Autowired DataSource dataSource){
    10. SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
    11. ssfb.setTypeAliasesPackage("com.domain");
    12. ssfb.setDataSource(dataSource);
    13. return ssfb;
    14. }
    15. @Bean
    16. public MapperScannerConfigurer getMapperScannerConfigurer(){
    17. MapperScannerConfigurer msc = new MapperScannerConfigurer();
    18. msc.setBasePackage("com.dao");
    19. return msc;
    20. }
    21. }

    jdbc.properties 

    1. jdbc.driver=com.mysql.cj.jdbc.Driver
    2. jdbc.url=jdbc:mysql://localhost:3306/spring_db?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8&useSSL=false
    3. jdbc.username=root
    4. jdbc.password=123456
    1. package com.service;
    2. import com.config.SpringConfig;
    3. import org.junit.Test;
    4. import org.junit.runner.RunWith;
    5. import org.springframework.beans.factory.annotation.Autowired;
    6. import org.springframework.test.context.ContextConfiguration;
    7. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    8. //设定spring专用的类加载器
    9. @RunWith(SpringJUnit4ClassRunner.class)
    10. //设定加载的spring上下文对应的配置
    11. @ContextConfiguration(classes = SpringConfig.class)
    12. public class UserServiceTest {
    13. @Autowired
    14. private AccountService accountService;
    15. @Test
    16. public void testTransfer(){
    17. accountService.transfer("Jock1","Jock2",100D);
    18. }
    19. }

    2.模板对象

    1.Spring模板对象

    TransactionTemplate

    JdbcTemplate

    RedisTemplate

    RabbitTemplate

    JmsTemplate

    HibernateTemplate

    RestTemplate

    2.JdbcTemplate

    提供标准的sql语句提供API

    1. public void save(Account account) {
    2. String sql = "insert into account(name,money)values(?,?)";
    3. jdbcTemplate.update(sql,account.getName(),account.getMoney());
    4. }

    3.NamedParameterJdbcTemplate 

    提供标准的sql语句提供API

    1. public void save(Account account) {
    2. String sql = "insert into account(name,money)values(:name,:money)";
    3. Map pm = new HashMap();
    4. pm.put("name",account.getName());
    5. pm.put("money",account.getMoney());
    6. jdbcTemplate.update(sql,pm);
    7. }

    4.RedisTemplate

    RedisTemplate对象结构

    1. public void changeMoney(Integer id, Double money) {
    2. redisTemplate.opsForValue().set("account:id:"+id,money);
    3. }
    4. public Double findMondyById(Integer id) {
    5. Object money = redisTemplate.opsForValue().get("account:id:" + id);
    6. return new Double(money.toString());
    7. }

    3.事务底层原理解析

    策略模式(Strategy Pattern)使用不同策略的对象实现不同的行为方式,策略对象的变化导致行为的变化

  • 相关阅读:
    数列分块入门
    B站-后台开发岗
    linux创建并使用service
    SAP-SD26-设定销售收入科目
    【vue3源码】二、vue3的响应系统分析
    计算机组成原理习题课第一章-1(唐朔飞)
    【MySQL】SQL优化
    油猴脚本(JavaScript)-练手-简单的随机音乐播放器
    工具链赋能百家,地平线开启智能驾驶量产的“马太效应”
    与伊人相约元宇宙——一次长谈为她讲清楚什么是元宇宙
  • 原文地址:https://blog.csdn.net/weixin_61611746/article/details/134516315