四、spring的JDBC模板和事务管理
Spring的JDBC模板
Spring是JavaEE开发的一站式框架,对各种持久化技术都提供了简单的模板
ORM持久化技术 | 模板类 |
JDBC | org.springframework.jdbc.core.JdbcTemplate |
Hibernate5.0 | org.springframework.orm.hibernate5.HibernateTemplate |
IBatis(MyBatis) | org.springframework.orm.ibatis.SqlMapClientTemplate |
JPA | org.springfrmaework.orm.jpa.JpaTemplate |
JDBC模板的基本使用
- 引入jar
- Spring项目的6个基础开发包
- 数据库驱动包
- Spring的JDBC模板的jar包
- 测试
- 编写测试类
- public class TestDemo {
- @Test
- public void demo() {
- //创建连接池
- DriverManagerDataSource dataSource = new DriverManagerDataSource();
- dataSource.setDriverClassName("com.mysql.jdbc.Driver");
- dataSource.setUrl("jdbc:mysql:///test");
- dataSource.setUsername("root");
- dataSource.setPassword("root");
- //创建jdbc模板
- JdbcTemplate template = new JdbcTemplate(dataSource);
- List<Map<String,Object>> list = template.queryForList("select * from user");
- for (Map<String, Object> map : list) {
- Set<String> keySet = map.keySet();
- Iterator<String> iterator = keySet.iterator();
- while (iterator.hasNext()) {
- String key = iterator.next();
- System.out.println(key+" : "+map.get(key));
- }
- }
- }
- }
- 测试结果
- id : 1
- name : test
- password : 0
- id : 2
- name : wxf
- password : 1
- id : 3
- name : admin
- password : 123
- id : 1
- 编写测试类
Spring管理模板和连接池
- 配置文件配置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"
- 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">
- <!-- 管理数据库连接池 -->
- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
- <property name="url" value="jdbc:mysql:///test"></property>
- <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
- <property name="username" value="root"></property>
- <property name="password" value="root"></property>
- </bean>
- <!-- 管理JDBC模板 -->
- <bean id="template" class="org.springframework.jdbc.core.JdbcTemplate">
- <property name="dataSource" ref="dataSource"/>
- </bean>
- </beans>
- <?xml version="1.0" encoding="UTF-8"?>
- 测试方法
- @Test
- public void demo2() {
- ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
- JdbcTemplate template = (JdbcTemplate) context.getBean("template");
- List<Map<String,Object>> list = template.queryForList("select * from user");
- for (Map<String, Object> map : list) {
- Set<String> keySet = map.keySet();
- Iterator<String> iterator = keySet.iterator();
- while (iterator.hasNext()) {
- String key = iterator.next();
- System.out.println(key+" : "+map.get(key));
- }
- }
- }
- @Test
Spring中使用开源数据库连接池
DBCP的使用
- 引入jar包
- com.springsource.org.apache.commons.pool-1.5.3.jar
- com.springsource.org.apache.commons.dbcp-1.2.2.osgi.jar
- Spring配置连接池
- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
- <property name="url" value="jdbc:mysql:///test"></property>
- <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
- <property name="username" value="root"></property>
- <property name="password" value="root"></property>
- </bean>
- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
C3P0的使用
- 引入jar包
- com.springsource.com.mchange.v2.c3p0-0.9.1.2.jar
- Spring配置连接池
- <!-- 管理c3p0数据库连接池 -->
- <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
- <property name="jdbcUrl" value="jdbc:mysql:///test"></property>
- <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
- <property name="user" value="root"></property>
- <property name="password" value="root"></property>
- </bean>
- <!-- 管理c3p0数据库连接池 -->
抽取连接池属性配置值到Properties文件
- 定义一个properties文件:jdbc.properties
- jdbc.url=jdbc:mysql:///test
- jdbc.driverClassName=com.mysql.jdbc.Driver
- jdbc.username=root
- jdbc.password=root
- jdbc.url=jdbc:mysql:///test
- Spring引入jdbc.properties文件
- 第一种:使用<bean>标签
- <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
- <property name="location" value="classpath:jdbc.properties"/>
- </bean>
- <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
- 第二种:使用<context:property-placeholder>标签
- <context:property-placeholder location="classpath:jdbc.properties" />
- 第一种:使用<bean>标签
- Spring配置文件使用jdbc.properties的属性值
- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
- <property name="url" value="${jdbc.url}"></property>
- <property name="driverClassName" value="${jdbc.driverClassName}"></property>
- <property name="username" value="${jdbc.username}"></property>
- <property name="password" value="${jdbc.password}"></property>
- </bean>
- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
Spring的事务管理
常用API
PlatformTransactionManager
- Spring的事务基础结构的中心接口,常用实现类
- DataSourceTransactionManager:使用JDBC管理事务
- HibernateTransactionManager:使用Hibernate管理事务
TransactionDefinition
- Spring的事务定义,用于定义事务相关的信息。例如,隔离级别、传播行为、是否只读、超时信息等
TransactionStatus
- 用于记录事务管理的过程中,事务的状态信息
Spring进行事务管理时,PlatformTransactionManager根据TransactionDefinition进行事务的管理,这个过程中会产生各种状态,将这些状态记录到TransactionStatus中
传播行为
基本认识
事务传播行为用来描述由某一个事务传播行为修饰的方法被嵌套进另一个方法的时事务如何传播
主要用来解决业务层方法(每个业务层方法有自己的事务)相互调用的问题
7种传播行为
- class TestServiceImpl01 {
- ...
- public void A() {
- testDao1.test1();
- testDao2.test2();
- }
- }
- class TestServiceImpl02 {
- ...
- public void B() {
- new TestServiceImpl01().A();//A操作
- testDao3.test3();//B操作
- testDao4.test4();//B操作
- }
- }
分类 | 传播行为类型 | 说明 |
多个操作在同一个事务中 (A、B操作在一个事务中) |
PROPAGATION_REQUIRED | 默认值,如果A中有事务,使用A中的事务;如果A中没有事务,创建一个新的事务,将操作(A、B)包含进来 |
PROPAGATION_SUPPORTS | 如果A中有事务,使用A中的事务;如果A中没有事务,就不使用事务 | |
PROPAGATION_MANDATORY | 如果A中有事务,使用A中的事务;如果A中没有事务,就抛出异常 | |
多个操作不在同一个事务中 (A、B操作不在一个事务中) |
PROPAGATION_REQUIRES_NEW | 如果A中有事务,将A的事务挂起,新建一个事务,只将自身操作(B)包含进来 |
PROPAGATION_NOT_SUPPORTED | 如果A中有事务,将A的事务挂起,不使用事务 | |
PROPAGATION_NEVER | 如果A中有事务,抛出异常 | |
嵌套式事务 | PROPAGATION_NESTED |
如果A中有事务,执行A事务,执行完成后设置一个保存点;再执行B中的操作,如果没有异常,执行通过;如果有异常 可以回滚到最初始位置(A操作前),也可以回滚到A操作后设置的保存点位置 |
基本使用
案例要求:
账户之间相互转账,一方转出的同时另一方必须转入才行
实现一:不使用事务管理
- 创建service层、dao层的接口和实现类
- dao层
- 接口
- package com.qf.tx.demo;
- public interface AccountDao {
- void addMoney(Long toId,Double money);
- void subMoney(Long fromId,Double money);
- }
- 实现类
- package com.qf.tx.demo;
- import org.springframework.jdbc.core.support.JdbcDaoSupport;
- import org.springframework.stereotype.Repository;
- @Repository("accountDao")
- public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {
- @Override
- public void addMoney(Long toId, Double money) {
- this.getJdbcTemplate().update("update account set amount=amount+? where id=?", money, toId);
- }
- @Override
- public void subMoney(Long fromId, Double money) {
- this.getJdbcTemplate().update("update account set amount=amount-? where id=?", money, fromId);
- }
- }
- 接口
- service层
- 接口
- package com.qf.tx.demo;
- public interface AccountService {
- void transerTo(Long fromId,Long toId,Double money);
- }
- 实现类
- package com.qf.tx.demo;
- import javax.annotation.Resource;
- import org.springframework.stereotype.Service;
- @Service("accountService")
- public class AccountServiceImpl implements AccountService{
- @Resource(name="accountDao")
- private AccountDao accountDao;
- public void setAccountDao(AccountDao accountDao) {
- this.accountDao = accountDao;
- }
- @Override
- public void transerTo(Long fromId, Long toId, Double money) {
- accountDao.subMoney(fromId, money);
- //int a = 1/0;
- accountDao.addMoney(toId, money);
- }
- }
- 接口
- dao层
- Spring管理service和dao的实现类
- <!-- 配置数据源连接池 -->
- <context:property-placeholder location="classpath:jdbc.properties" />
- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
- <property name="url" value="${jdbc.url}"></property>
- <property name="driverClassName" value="${jdbc.driverClassName}"></property>
- <property name="username" value="${jdbc.username}"></property>
- <property name="password" value="${jdbc.password}"></property>
- </bean>
- <!-- Spring管理dao -->
- <bean id="accountDao" class="com.qf.tx.demo.AccountDaoImpl">
- <property name="dataSource" ref="dataSource"></property>
- </bean>
- <!-- Spring管理service -->
- <bean id="accountService" class="com.qf.tx.demo.AccountServiceImpl">
- <property name="accountDao" ref="accountDao"></property>
- </bean>
- <!-- 配置数据源连接池 -->
- 测试
- package com.qf.tx.demo;
- import javax.annotation.Resource;
- import org.junit.Test;
- import org.junit.runner.RunWith;
- import org.springframework.test.context.ContextConfiguration;
- import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
- @RunWith(SpringJUnit4ClassRunner.class)
- @ContextConfiguration("classpath:applicationContext_tx.xml")
- public class TestDemo {
- @Resource(name="accountService")
- private AccountService accountService;
- @Test
- public void test() {
- accountService.transerTo(1L, 2L, 100d);
- }
- }
实现二:编程式事务管理
- 配置事务平台管理器
- <!-- 配置事务平台管理器 -->
- <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
- <property name="dataSource" ref="dataSource"></property>
- </bean>
- <!-- 配置事务平台管理器 -->
- 配置事务管理模板
- 事务管理模板
- 使用TransactionTemplate 不需要显式地开始事务,甚至不需要显式地提交事务。这些步骤都由模板完成。
- 出现异常时,应通过TransactionStatus 的setRollbackOnly 显式回滚事务。
- TransactionTemplate 的execute 方法接收一个TransactionCallback 实例。Callback 也是Spring 的经典设计,用于简化用户操作
- 配置
- <!-- 配置简化管理事务的模板 -->
- <bean id="txTemplate" class="org.springframework.transaction.support.TransactionTemplate">
- <property name="transactionManager" ref="txManager"/>
- </bean>
- <!-- 配置简化管理事务的模板 -->
- 事务管理模板
- service层注入事务管理模板,用于管理事务
- <!-- Spring管理service,在service层注入事务管理的模板 -->
- <bean id="accountService" class="com.qf.tx.demo.AccountServiceImpl">
- <property name="accountDao" ref="accountDao"/>
- <property name="txTemplate" ref="txTemplate"/>
- </bean>
- <!-- Spring管理service,在service层注入事务管理的模板 -->
- 修改service的实现类
- package com.qf.tx.demo;
- import javax.annotation.Resource;
- import org.springframework.stereotype.Service;
- import org.springframework.transaction.TransactionStatus;
- import org.springframework.transaction.support.TransactionCallback;
- import org.springframework.transaction.support.TransactionCallbackWithoutResult;
- import org.springframework.transaction.support.TransactionTemplate;
- @Service("accountService")
- public class AccountServiceImpl implements AccountService{
- @Resource(name="accountDao")
- private AccountDao accountDao;
- public void setAccountDao(AccountDao accountDao) {
- this.accountDao = accountDao;
- }
- @Resource(name="txTemplate")
- private TransactionTemplate txTemplate;
- public void setTxTemplate(TransactionTemplate txTemplate) {
- this.txTemplate = txTemplate;
- }
- @Override
- public void transerTo(final Long fromId, final Long toId, final Double money) {
- txTemplate.execute(new TransactionCallbackWithoutResult() {
- @Override
- protected void doInTransactionWithoutResult(TransactionStatus status) {
- accountDao.subMoney(fromId, money);
- int a = 1/0;
- accountDao.addMoney(toId, money);
- }
- });
- }
- }
实现三:声明式事务管理
声明式事务管理
- 不需要修改代码就可以实现事务管理
- 采用AOP实现,所以可以使用XML和注解两种方式来实现
XML方式
- 使用实现一的接口和实现类即可,不需要修改代码
- 引入AOP开发需要的jar包
- spring-aop-4.2.4.RELEASE.jar
- spring-aspects-4.2.4.RELEASE.jar
- com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
- com.springsource.org.aopalliance-1.0.0.jar
- 配置事务平台管理器
- <!-- 配置事务平台管理器 -->
- <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
- <property name="dataSource" ref="dataSource"></property>
- </bean>
- <!-- 配置事务平台管理器 -->
- AOP配置
- 配置切面
- <!-- 配置事务的增强 -->
- <tx:advice id="txAdvice" transaction-manager="txManager">
- <tx:attributes>
- <tx:method name="trans*" propagation="REQUIRED" />
- </tx:attributes>
- </tx:advice>
- <!-- 配置事务的增强 -->
- 将切面应用到目标类
- <!-- 配置AOP -->
- <aop:config>
- <aop:pointcut expression="execution(* com.qf.tx.demo.AccountServiceImpl.*(..))" id="pointcut"/>
- <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
- </aop:config>
- <!-- 配置AOP -->
- 配置切面
注解方式
- 引入AOP开发需要的jar包
- spring-aop-4.2.4.RELEASE.jar
- spring-aspects-4.2.4.RELEASE.jar
- com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
- com.springsource.org.aopalliance-1.0.0.jar
- 配置事务平台管理器
- <!-- 配置事务平台管理器 -->
- <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
- <property name="dataSource" ref="dataSource"></property>
- </bean>
- <!-- 配置事务平台管理器 -->
- 开启注解事务
- <!-- 开启注解事务 -->
- <tx:annotation-driven transaction-manager="txManager"/>
- <!-- 开启注解事务 -->
- service层添加注解
- @Transactional
- @Service("accountService")
- public class AccountServiceImpl implements AccountService
- @Transactional
四、spring的JDBC模板和事务管理的更多相关文章
- java框架之Spring(3)-JDBC模板使用&事务管理
下面内容使用到的 jar 包下载 JDBC模板使用 入门 1.导包,如要导入 Spring 的基本开发包.数据库驱动包.Spring 提供的 JDBC 模板包,如下: 2.测试: @Test publ ...
- 【Spring实战】—— 16 基于JDBC持久化的事务管理
前面讲解了基于JDBC驱动的Spring的持久化管理,本篇开始则着重介绍下与事务相关的操作. 通过本文你可以了解到: 1 Spring 事务管理的机制 2 基于JDBC持久化的事务管理 Spring的 ...
- 创建JDBC模板简化代码、JDBC应用的事务管理以及连接池的作用
一.创建JDBC模板简化代码 一个简单的查询.要做这么一大堆事情,并且还要处理异常,我们不防来梳理一下: 1.获取connection 2.获取statement 3.获取resultset 4 ...
- Spring 简单而强大的事务管理功能
开始之前 关于本教程 本教程将深入讲解 Spring 简单而强大的事务管理功能,包括编程式事务和声明式事务.通过对本教程的学习,您将能够理解 Spring 事务管理的本质,并灵活运用之. 先决条件 本 ...
- 事务隔离级别与传播机制,spring+mybatis+atomikos实现分布式事务管理
1.事务的定义:事务是指多个操作单元组成的合集,多个单元操作是整体不可分割的,要么都操作不成功,要么都成功.其必须遵循四个原则(ACID). 原子性(Atomicity):即事务是不可分割的最小工作单 ...
- Spring事务隔离级别与传播机制详解,spring+mybatis+atomikos实现分布式事务管理
原创说明:本文为本人原创作品,绝非他处转载,转账请注明出处 1.事务的定义:事务是指多个操作单元组成的合集,多个单元操作是整体不可分割的,要么都操作不成功,要么都成功.其必须遵循四个原则(ACID). ...
- Spring+JTA+Atomikos+mybatis分布式事务管理
我们平时的工作中用到的Spring事务管理是管理一个数据源的.但是如果对多个数据源进行事务管理该怎么办呢?我们可以用JTA和Atomikos结合Spring来实现一个分布式事务管理的功能.了解JTA可 ...
- Spring的jdbc模板1
Spring是EE开发的一站式框架,有EE开发的每一层解决方案.Spring对持久层也提供了解决方案:ORM模块和jdbc模块,ORM模块在整合其他框架的时候使用 Spring提供了很多的模板用于简化 ...
- spring boot配置mybatis和事务管理
spring boot配置mybatis和事务管理 一.spring boot与mybatis的配置 1.首先,spring boot 配置mybatis需要的全部依赖如下: <!-- Spri ...
随机推荐
- Intellij 选择profile
注意有3个地方需要改
- mysql sqlyog提示2058错误或者用Navicat连接本机Docker的Mysql 和一些问题的解决方案
1. 下载Mysql的Docker镜像: [plain] view plain copy$ docker search mysql (搜索mysql镜像) $ docker pull mysql ( ...
- 【Leetcode周赛】从contest-91开始。(一般是10个contest写一篇文章)
Contest 91 (2018年10月24日,周三) 链接:https://leetcode.com/contest/weekly-contest-91/ 模拟比赛情况记录:第一题柠檬摊的那题6分钟 ...
- 公私钥,数字证书,https
1.密钥对,在非对称加密技术中,有两种密钥,分为私钥和公钥,私钥是密钥对所有者持有,不可公布,公钥是密钥对持有者公布给他人的. 2.公钥,公钥用来给数据加密,用公钥加密的数据只能使用私钥解密. 3.私 ...
- 前端每日实战:53# 视频演示如何用纯 CSS 创作一个文本淡入淡出的 loader 动画
效果预览 按下右侧的"点击预览"按钮可以在当前页面预览,点击链接可以全屏预览. https://codepen.io/comehope/pen/ERwpeG 可交互视频 此视频是可 ...
- 【leetcode】981. Time Based Key-Value Store
题目如下: Create a timebased key-value store class TimeMap, that supports two operations. 1. set(string ...
- MYSQL5.7.9改密码相关设置
Centos7上,对MySQL5.7开启远程连接. 1.修改/etc/my.cnf [mysqld] validate_password=off 2.命令行进入mysql use mysql; GRA ...
- 报错——userdel: user hhh is currently used by process 9218
报错 userdel: user hhh is currently used by process 9218 [root@centos71 ~]# useradd hhh [root@centos71 ...
- 如何在pycharm上创建分支,并且把它推送到远端仓库
注意创建的分支名 ,如果远端仓库没有pycharm中创建的分支名时 此时远端仓库会创建一个分支出来 这是就方便了代码的管理 具体步骤如下图操作步骤 推送上去搞定
- Orcad Capture元件库介绍--Cadence Allegro
绘制原理图和PCB,最好有自己的元件封装.元件库 ORCAD CAPTURE元件库介绍 AMPLIFIER.OLB amplifier 共182个零件,存放模拟放大器IC,如CA3280,TL027C ...