01_Spring的JdbcTemplate模板类

spring(jdbctemplate、事务管理) - 图2A.Spring提供有DAO支持模板类,功能类似于Apache 的DbUtils.
spring(jdbctemplate、事务管理) - 图3B.常用API
spring(jdbctemplate、事务管理) - 图4spring(jdbctemplate、事务管理) - 图5public int update(String sql, Object… args)
执行DML语句.增、删、改语句
spring(jdbctemplate、事务管理) - 图6spring(jdbctemplate、事务管理) - 图7public T query(String sql, ResultSetExtractor rse, Object… args)
执行DQL语句.查询单条/多条记录
spring(jdbctemplate、事务管理) - 图8C.基础实例
spring(jdbctemplate、事务管理) - 图9a.导入jar包

  1. // 核 心 包 (4 个 )
  2. springbeans5.1.8.RELEASE.jar springcontext5.1.8.RELEASE.jar springcore5.1.8.RELEASE.jar springexpression5.1.8.RELEASE.jar
  3. // 日 志 包 (1 个 )
  4. springjcl5.1.8.RELEASE.jar
  5. //jdbc 包 (1 个 )
  6. springjdbc5.1.8.RELEASE.jar
  7. // 事 务 包 (1 个 )
  8. springtx5.1.8.RELEASE.jar
  9. //c3p0包(2个) c3p0‐0.9.5.4.jar
  10. mchangecommonsjava0.2.16.jar
  11. //mysql 驱 动 包 (1 个 )
  12. mysqlconnectorjava8.0.11.jar


spring(jdbctemplate、事务管理) - 图10b.增删改查

  1. //增删改
  2. ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
  3. JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
  4. jdbcTemplate.update("update tb_account set username = ? where id = ?", "b", 1);
  5. //查询单条记录
  6. Account account = jdbcTemplate.query("select * from tb_account where id = ?", new ResultSetExtractor < Account > () {@Override public Account extractData(ResultSet resultSet) throws SQLException,
  7. DataAccessException {
  8. Account existAccount = null;
  9. while (resultSet.next()) {
  10. existAccount = new Account(resultSet.getInt("id"), resultSet.getString("username"), resultSet.getDoub le("money"));
  11. }
  12. return existAccount;
  13. }
  14. },
  15. 1);
  16. System.out.println(account);
  17. //查询多条记录
  18. List < Account > accountList = jdbcTemplate.query("select * from tb_account", new ResultSetExtractor < List < Account >> () {@Override public List < Account > extractData(ResultSet resultSet) throws SQLException,
  19. DataAccessException {
  20. List < Account > existAccountList = new ArrayList < >();
  21. while (resultSet.next()) {
  22. Account existAccount = new Account(resultSet.getInt("id"), resultSet.getString("username"), resultSet.getDoub le("money"));
  23. existAccountList.add(existAccount);
  24. }
  25. return existAccountList;
  26. }
  27. });
  28. System.out.println(accountList);

02_使用xml声明形式开发JDBCTemplate

spring(jdbctemplate、事务管理) - 图11前提
spring(jdbctemplate、事务管理) - 图12需要导入aop的jar包
spring(jdbctemplate、事务管理) - 图13需要导入Spring的测试jar包
spring(jdbctemplate、事务管理) - 图14A.在DAO中声明JDBCTemplate变量,提供set方法

  1. public class UserDao {
  2. public JdbcTemplate jdbcTemplate;
  3. public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
  4. this.jdbcTemplate = jdbcTemplate;
  5. }
  6. public List < User > addUser() {∙∙∙∙∙∙
  7. }
  8. }

spring(jdbctemplate、事务管理) - 图15B.编写外部properties格式文件
spring(jdbctemplate、事务管理) - 图16C.将DAO声明为Bean,为其注入JDBCTemplate
spring(jdbctemplate、事务管理) - 图17D.声明JDBCTemplate的Bean,为其注入DataSource

  1. <?xml version="1.0" encoding="UTF‐8"?>
  2. <beans
  3. xmlns="http://www.springframework.org/schema/beans"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema‐instance"
  5. xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring‐beans.xsd
  7. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring‐context.xsd">
  8. <bean id="userDao" class="com.qzw.dao.UserDao">
  9. <property name="jdbcTemplate" ref="jdbcTemplate"></property>
  10. </bean>
  11. <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
  12. <property name="dataSource" ref="dataSource"></property>
  13. </bean>
  14. <context:propertyplaceholder location="classpath:c3p0.properties"></context:propertyplaceholder>
  15. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  16. <property name="driverClass" value="${c3p0.driverClass}"></property>
  17. <property name="jdbcUrl" value="${c3p0.jdbcUrl}"></property>
  18. <property name="user" value="${c3p0.user}"></property>
  19. <property name="password" value="${c3p0.password}"></property>
  20. </bean>
  21. </beans>

spring(jdbctemplate、事务管理) - 图18E.代码测试

  1. @RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = {
  2. "classpath:spring01.xml"
  3. })
  4. public class DaoTest {
  5. @Resource private UserDao userDao;
  6. @Test public void queryAll() {
  7. System.out.println(userDao.addUser());
  8. }
  9. }


03_Spring事务概念

spring(jdbctemplate、事务管理) - 图19A.Spring框架处理事务的方式
spring(jdbctemplate、事务管理) - 图20A,编程式事务管理(TransactionTemplate)
spring(jdbctemplate、事务管理) - 图21B,声明式事务管理
spring(jdbctemplate、事务管理) - 图22a,xml声明
spring(jdbctemplate、事务管理) - 图23b,注解声明

04_Spring编程式事务之PlatformTransactionManager

spring(jdbctemplate、事务管理) - 图24spring 的事务管理器,提供常用的操作事务的方法

spring(jdbctemplate、事务管理) - 图25
spring(jdbctemplate、事务管理) - 图26注意事项
spring(jdbctemplate、事务管理) - 图27PlatformTransactionManager 是接口类型,不同的 Dao 层技术则有不同的实现类
spring(jdbctemplate、事务管理) - 图28Dao 层技术是jdbc 或 mybatis 时:DataSourceTransactionManager
spring(jdbctemplate、事务管理) - 图29Dao 层技术是hibernate时:HibernateTransactionManager

05_Spring编程式事务之TransactionDefinition

spring(jdbctemplate、事务管理) - 图30事务的定义信息对象,里面有如下方法
spring(jdbctemplate、事务管理) - 图31
spring(jdbctemplate、事务管理) - 图32设置事务隔离级别
spring(jdbctemplate、事务管理) - 图33TransactionDefinition是接口,设置操作都在DefaultTransactionDefinition类中
ISOLATION_DEFAULT : 设置成数据库默认的隔离级别,MySQL为REPEATABLE_READ ISOLATION_READ_UNCOMMITTED : 设置为读未提交
ISOLATION_READ_COMMITTED : 设置为读已提交
ISOLATION_REPEATABLE_READ : 设置为可重复读
ISOLATION_SERIALIZABLE : 设置为串行化
spring(jdbctemplate、事务管理) - 图34设置事务传播行为
spring(jdbctemplate、事务管理) - 图35REQUIRED:如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。一般的选择(默认值)
spring(jdbctemplate、事务管理) - 图36SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行(没有事务)
spring(jdbctemplate、事务管理) - 图37MANDATORY:使用当前的事务,如果当前没有事务,就抛出异常
spring(jdbctemplate、事务管理) - 图38REQUERS_NEW:新建事务,如果当前在事务中,把当前事务挂起。
spring(jdbctemplate、事务管理) - 图39NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起
spring(jdbctemplate、事务管理) - 图40NEVER:以非事务方式运行,如果当前存在事务,抛出异常
spring(jdbctemplate、事务管理) - 图41NESTED:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行
REQUIRED 类似的操作
spring(jdbctemplate、事务管理) - 图42超时时间:默认值是-1,没有超时限制。如果有,以秒为单位进行设置
是否只读:建议查询时设置为只读

06_Spring编程式事务之TransactionStatus

spring(jdbctemplate、事务管理) - 图43事务具体的运行状态,方法介绍如下。
image.png

07_Spring事务环境搭建

spring(jdbctemplate、事务管理) - 图45jar包
image.png

spring(jdbctemplate、事务管理) - 图47spring.xml配置文件

  1. <context:componentscan basepackage="com.qzw"></context:componentscan>
  2. <context:propertyplaceholder location="c3p0.properties"></context:propertyplaceholder>
  3. <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
  4. <property name="dataSource" ref="dataSource"></property>
  5. </bean>
  6. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  7. <property name="driverClass" value="${c3p0.driverClass}"></property>
  8. <property name="jdbcUrl" value="${c3p0.jdbcUrl}"></property>
  9. <property name="user" value="${c3p0.user}"></property>
  10. <property name="password" value="${c3p0.password}"></property>
  11. </bean>

spring(jdbctemplate、事务管理) - 图48service层

  1. @Service
  2. public class AccountServiceImpl implements AccountService {
  3. @Autowired
  4. private AccountDao accoutDao;@Autowired private SelfTransactionManager selfTransactionManager;
  5. @Override
  6. public void transfer(String outName, String inName, int money) {
  7. try {
  8. accoutDao.outMoney("张三", 100);
  9. int num = 1 / 0;
  10. accoutDao.inMoney("李四", 100);
  11. } catch(Exception e) {
  12. e.printStackTrace();
  13. }
  14. }
  15. }

spring(jdbctemplate、事务管理) - 图49dao层

  1. @Repository
  2. public class AccountDaoImpl implements AccountDao {
  3. @Autowired
  4. private JdbcTemplate jdbcTemplate;
  5. @Override
  6. public void inMoney(String inName, int money) throws Exception {
  7. jdbcTemplate.update("update tb_account set money = money + ? where username =
  8. ?", money, inName);
  9. }
  10. @Override
  11. public void outMoney(String outName, int money) throws Exception {
  12. jdbcTemplate.update("update tb_account set money = money ? where username =
  13. ?", money, outName);
  14. }
  15. }

08_Spring编程式事务基础版

spring(jdbctemplate、事务管理) - 图50spring.xml配置文件中,加入事务管理器: DataSourceTransactionManager

  1. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  2. <property name="dataSource" ref="dataSource"></property>
  3. </bean>

spring(jdbctemplate、事务管理) - 图51自定义事务管理器

  1. @Component
  2. public class SelfTransactionManager {
  3. @Autowired
  4. private DataSourceTransactionManager transactionManager;
  5. //手动开启事务
  6. public TransactionStatus begin() {
  7. DefaultTransactionAttribute attribute = new DefaultTransactionAttribute();
  8. TransactionStatus transactionStatus = transactionManager.getTransaction(attribute);
  9. return transactionStatus;
  10. }
  11. //开启事务
  12. public void commit(TransactionStatus transactionStatus) {
  13. transactionManager.commit(transactionStatus);
  14. }
  15. //回滚
  16. public void rollback(TransactionStatus transactionStatus) {
  17. transactionManager.rollback(transactionStatus);
  18. }
  19. }

spring(jdbctemplate、事务管理) - 图52改造service层代码,加入事务管理

  1. @Service
  2. public class AccountServiceImpl implements AccountService {
  3. @Autowired
  4. private AccountDao accoutDao;
  5. @Autowired
  6. private SelfTransactionManager selfTransactionManager;
  7. @Override
  8. public void transfer(String outName, String inName, int money) {
  9. TransactionStatus status = selfTransactionManager.begin();
  10. try {
  11. accoutDao.outMoney("张三", 100);
  12. int num = 1 / 0;
  13. accoutDao.inMoney("李四", 100);
  14. } catch (Exception e) {
  15. e.printStackTrace();
  16. selfTransactionManager.rollback(status);
  17. }
  18. selfTransactionManager.commit(status);
  19. }
  20. }

09_Spring编程式事务优化版

spring(jdbctemplate、事务管理) - 图53在基础版中,如果需要事务管理的业务方法较多,那么就需要考虑将事务管理抽取成一个公 共的环绕通知,这样就只需要维护一处事务管理通知了!

spring(jdbctemplate、事务管理) - 图54自定义事务通知类TxAdvice

  1. public class TxAdvice {
  2. @Resource
  3. private SelfTransactionManager selfTransactionManager;
  4. public void txAround(ProceedingJoinPoint pjp) {
  5. System.out.println("txAround");
  6. TransactionStatus status = selfTransactionManager.begin();
  7. try {
  8. pjp.proceed();
  9. } catch (Throwable throwable) {
  10. throwable.printStackTrace();
  11. selfTransactionManager.rollback(status);
  12. }
  13. selfTransactionManager.commit(status);
  14. }
  15. }


spring(jdbctemplate、事务管理) - 图55配置环绕通知

  1. .......
  2. <aop:config>
  3. <aop:aspect ref="txAdvice">
  4. <aop:around method="txAround" pointcut="execution(* *..*Service.*(..))"></aop:around>
  5. </aop:aspect>
  6. </aop:config>
  7. <bean id="txAdvice" class="com.qzw.tx.TxAdvice"></bean>

spring(jdbctemplate、事务管理) - 图56service层代码
spring(jdbctemplate、事务管理) - 图57注意service层的异常不能使用try方式捕获,要抛出.这样,环绕通知才能截获到发生的异常进行处理!!!

  1. @Service
  2. public class AccountServiceImpl implements AccountService {
  3. @Autowired
  4. private AccountDao accoutDao;
  5. @Override
  6. public void transfer(String outName, String inName, int money)
  7. throws Exception {
  8. accoutDao.outMoney("张三", 100);
  9. int num = 1 / 0;
  10. accoutDao.inMoney("李四", 100);
  11. }
  12. }

10_声明式事务概念及入门

spring(jdbctemplate、事务管理) - 图58A.思路分析:
spring(jdbctemplate、事务管理) - 图59将编程式事务中的通用代码抽取出来,制作成独立的around通知使用AOP工作原理,将事务管理的代码动态织入到原始方法中。由于该功能使用量较大,Spring已经将该通知制作完毕。
spring(jdbctemplate、事务管理) - 图60B.开发步骤:
spring(jdbctemplate、事务管理) - 图61a.开启事务tx命名空间
spring(jdbctemplate、事务管理) - 图62b.配置事务通知
spring(jdbctemplate、事务管理) - 图63c.将事务通知配置到切入点

  1. <!‐‐
  2. 配置事务通知
  3. id:事务通知唯一标识
  4. transactionmanager:事务管理类
  5. ‐‐>
  6. <tx:advice id="txAdvice" transactionmanager="transactionManager">
  7. <tx:attributes>
  8. <tx:method name="transfer"/>
  9. </tx:attributes>
  10. </tx:advice>
  11. <!‐‐
  12. 将事务通知配置到切入点
  13. ‐‐>
  14. <aop:config>
  15. <!‐‐配置事务切面‐‐>
  16. <aop:advisor adviceref="txAdvice" pointcut="execution(* *..*Service.*(..))">
  17. </aop:advisor>
  18. </aop:config>

11_声明式事务属性说明

spring(jdbctemplate、事务管理) - 图64read-only: 设置是否只读.增删改为false,查询为true
spring(jdbctemplate、事务管理) - 图65propagation: 设置事务传播
spring(jdbctemplate、事务管理) - 图66isolation: 设置隔离级别

  1. <tx:advice transactionmanager="transactionManager" id="txAdvice">
  2. <tx:attributes >
  3. <tx:method name="transfer" readonly="false" propagation="REQUIRED" isolation="REPEATABLE_READ" />
  4. <tx:method name="add*" readonly="false" propagation="REQUIRED" isolation="DEFAULT"></tx:method>
  5. <tx:method name="update*" readonly="false" propagation="REQUIRED" isolation="DEFAULT"></tx:method>
  6. <tx:method name="delete*" readonly="false" propagation="REQUIRED" isolation="DEFAULT"></tx:method>
  7. <tx:method name="select*" readonly="true" propagation="REQUIRED" isolation="DEFAULT"></tx:method>
  8. </tx:attributes>
  9. </tx:advice>


12,注解式事务

spring(jdbctemplate、事务管理) - 图67A.步骤
spring(jdbctemplate、事务管理) - 图68a.在配置文件中,开启注解式事务,为其指定事务管理器

  1. <tx:annotationdriven transactionmanager="transactionManager">
  2. </tx:annotationdriven>

spring(jdbctemplate、事务管理) - 图69b.对要添加事务的类、接口、方法上方声明@Transactional

  1. @Service
  2. public class AccountServiceImpl implements AccountService {
  3. @Autowired
  4. private AccountDao accoutDao;
  5. @Transactional(readOnly = false, isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED)
  6. @Override
  7. public void transfer(String outName, String inName, int money)
  8. throws Exception {
  9. accoutDao.outMoney("张三", 100);
  10. int num = 1 / 0;
  11. accoutDao.inMoney("李四", 100);
  12. }
  13. }