共计 27183 个字符,预计需要花费 68 分钟才能阅读完成。
1、JdbcTemplate 概述
1.1、什么是 JdbcTemplate
JdbcTemplate 是 Spring 对 JDBC 的封装,目的是使 JDBC 更加易于使用。JdbcTemplate 是 Spring 的一部分。JdbcTemplate 处理了资源的建立和释放。他帮助我们避免一些常见的错误,比如忘了总要关闭连接。他运行核心的 JDBC 工作流,如 Statement 的建立和执行,而我们只需要提供 SQL 语句和提取结果。
1.2、Spring 中其他操作模板
操作关系型数据的:
JdbcTemplate
HibernateTemplate
操作 nosql 数据库的:
RedisTemplate
操作消息队列的:
JmsTemplate
1.3、JdbcTemplate 对象产生
org.springframework.jdbc.core.JdbcTemplate 类
public JdbcTemplate() {
}
public JdbcTemplate(DataSource dataSource) {setDataSource(dataSource);
afterPropertiesSet();}
public JdbcTemplate(DataSource dataSource, boolean lazyInit) {setDataSource(dataSource);
setLazyInit(lazyInit);
afterPropertiesSet();}
注意:
lazyInit 是否延迟初始化 SQLExceptionTranslator
1.4、JdbcTemplate 常用方法
**execute 方法:** 可以用于执行任何 SQL 语句,一般用于执行 DDL 语句;
**update 方法及 batchUpdate 方法:**update 方法用于执行新增、修改、删除等语句;batchUpdate 方法用于执行批处理相关语句;
**query 方法及 queryForXXX 方法:** 用于执行查询相关语句;
**call 方法:** 用于执行存储过程、函数相关语句。
2、JdbcTemplate 使用 - 上
2.1、创建项目
创建 maven 项目 spring007
2.2、导入 jar 包
一个是 jdbc、tx 的 jar 包
<?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>com.tyschool</groupId>
<artifactId>spring007</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.13.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.2.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.3</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.6</version>
</dependency>
</dependencies>
</project>
2.3、编写配置文件
applicationContext.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 id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 连接数据库的必备信息 -->
<property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://192.168.1.123:3306/spring?serverTimezone=UTC"></property>
<property name="user" value="root"></property>
<property name="password" value="Root12345"></property>
</bean>
<!-- 配置一个数据库的操作模板:JdbcTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
2.4、创建 javabean
Manager.java
package com.tyschool.spring007.javabean;
import java.io.Serializable;
import java.util.Date;
public class Manager implements Serializable {private int mid;
private String uname;
private String pword;
private Date zcsj;
public int getMid() {return mid;
}
public void setMid(int mid) {this.mid = mid;
}
public String getUname() {return uname;
}
public void setUname(String uname) {this.uname = uname;
}
public String getPword() {return pword;
}
public void setPword(String pword) {this.pword = pword;
}
public Date getZcsj() {return zcsj;
}
public void setZcsj(Date zcsj) {this.zcsj = zcsj;
}
@Override
public String toString() {return "Manager{" +
"mid=" + mid +
", uname='" + uname + '\'' +
", pword='" + pword + '\'' +
", zcsj=" + zcsj +
'}';
}
}
2.5、创建持久层
IManagerDao.java
import com.tyschool.spring007.javabean.Manager;
import java.util.List;
public interface IManagerDao {public List findAll();
public Manager findById(int mid);
public int updateManager(Manager m);
public int addManager(Manager m);
public int deleteManager(int mid);
public List findByName(String name);
public int allCount();
}
ManagerDaoImpl.java
import com.tyschool.spring007.javabean.Manager;
import com.tyschool.spring007.manager.dao.IManagerDao;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class ManagerDaoImpl implements IManagerDao {private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {this.jdbcTemplate = jdbcTemplate;
}
public List findAll() {String sql="select * from manager";
List<Manager> list=jdbcTemplate.query(sql,new BeanPropertyRowMapper<Manager>(Manager.class));
return list;
}
public Manager findById(int mid) {String sql="select * from manager where mid=?";
Manager m=jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<Manager>(Manager.class),mid);
return m;
}
public int updateManager(Manager m) {String sql="update manager set uname=?,pword=?,zcsj=? where mid=?";
int n=jdbcTemplate.update(sql,m.getUname(),m.getPword(),m.getZcsj(),m.getMid());
return n;
}
public int addManager(Manager m) {String sql="insert into manager(uname,pword,zcsj)values(?,?,?)";
int n=jdbcTemplate.update(sql,m.getUname(),m.getPword(),m.getZcsj());
return n;
}
public int deleteManager(int mid) {String sql="delete from manager where mid=?";
int n=jdbcTemplate.update(sql,mid);
return n;
}
public List findByName(String name) {String sql="select * from manager where uname like ?";
List<Manager> list=jdbcTemplate.query(sql,new BeanPropertyRowMapper<Manager>(Manager.class),name);
return list;
}
public int allCount() {String sql="select count(*) from manager";
int n=jdbcTemplate.queryForObject(sql,Integer.class);
return n;
}
}
3、JdbcTemplate 使用 - 下
3.1、创建业务层
IManagerService.java
import com.tyschool.spring007.javabean.Manager;
import java.util.List;
public interface IManagerService {public List findAll();
public Manager findById(int mid);
public int updateManager(Manager m);
public int addManager(Manager m);
public int deleteManager(int mid);
public List findByName(String name);
public int allCount();
}
ManagerServiceImpl.java
import com.tyschool.spring007.javabean.Manager;
import com.tyschool.spring007.manager.dao.IManagerDao;
import com.tyschool.spring007.manager.service.IManagerService;
import java.util.List;
public class ManagerServiceImpl implements IManagerService {
IManagerDao managerDao;
public void setManagerDao(IManagerDao managerDao) {this.managerDao = managerDao;
}
public List findAll() {return managerDao.findAll();}
public Manager findById(int mid) {return managerDao.findById(mid);
}
public int updateManager(Manager m) {return managerDao.updateManager(m);
}
public int addManager(Manager m) {return managerDao.addManager(m);
}
public int deleteManager(int mid) {return managerDao.deleteManager(mid);
}
public List findByName(String name) {return managerDao.findByName(name);
}
public int allCount() {return managerDao.allCount();}
}
3.2、修改配置文件
<bean id="managerDaoImpl" class="com.tyschool.spring007.manager.dao.impl.ManagerDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
<bean id="managerServiceImpl" class="com.tyschool.spring007.manager.service.impl.ManagerServiceImpl">
<property name="managerDao" ref="managerDaoImpl"></property>
</bean>
3.3、创建测试类
STest.java
import com.tyschool.spring007.javabean.Manager;
import com.tyschool.spring007.manager.service.IManagerService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.Date;
import java.util.List;
import java.util.Map;
public class STest {ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
IManagerService managerService=(IManagerService) ac.getBean("managerServiceImpl");
@Test
public void deleteManager(){managerService.deleteManager(4);
}
@Test
public void addManager(){Manager m=new Manager();
m.setUname("李攻");
m.setPword("zhangsan");
m.setZcsj(new Date());
managerService.addManager(m);
}
@Test
public void updateManager(){Manager m=new Manager();
m.setMid(5);
m.setUname("李四");
m.setPword("lisi");
m.setZcsj(new Date());
managerService.updateManager(m);
}
@Test
public void findAll(){List<Manager> list= managerService.findAll();
for(Manager m:list){System.out.println(m);
}
}
@Test
public void findById(){Manager m=managerService.findById(5);
System.out.println(m);
}
@Test
public void findByName(){List<Manager> list=managerService.findByName("李 %");
for(Manager m:list){System.out.println(m);
}
}
@Test
public void allCount(){int n= managerService.allCount();
System.out.println(n);
}
}
4、数据源配置
4.1、C3P0 数据源
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.3</version>
</dependency>
<!-- 配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 连接数据库的必备信息 -->
<property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://192.168.1.123:3306/spring?serverTimezone=UTC"></property>
<property name="user" value="root"></property>
<property name="password" value="Root12345"></property>
</bean>
4.2、DBCP 数据源
需要导入二个 jar 包,commons-dbcp.jar, commons-pool.jar
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.7.0</version>
</dependency>
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://192.168.1.123:3306/spring?serverTimezone=UTC"></property>
<property name="username" value="root"></property>
<property name="password" value="Root12345"></property>
</bean>
4.3、Druid 数据源
需要导入一个 jar 包,druid.jar
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.22</version>
</dependency>
<bean id = "dataSource" class = "com.alibaba.druid.pool.DruidDataSource" destroy-method = "close" >
<!-- 数据库基本信息配置 -->
<property name = "driverClassName" value = "com.mysql.cj.jdbc.Driver" />
<property name = "url" value = "jdbc:mysql://192.168.1.123:3306/spring?serverTimezone=UTC" />
<property name = "username" value = "root" />
<property name = "password" value = "Root12345" />
</bean>
4.4、Spring 内置数据源
需要导入一个 jar 包,spring-jdbc.jar
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://192.168.1.123:3306/spring?serverTimezone=UTC"></property>
<property name="username" value="root"></property>
<property name="password" value="Root12345"></property>
</bean>
4.5、优化配置
4.5.1、创建一个 db.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.1.123:3306/spring?serverTimezone=UTC
jdbc.username=root
jdbc.password=Root12345
4.5.2、引入 db.properties
方式一:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:db.properties"/>
</bean>
方式二:
<context:property-placeholder location="classpath:db.properties"/>
4.5.3、修改数据源配置
<bean id = "dataSource" class = "com.alibaba.druid.pool.DruidDataSource" destroy-method = "close" >
<!-- 数据库基本信息配置 -->
<property name = "driverClassName" value = "${jdbc.driver}" />
<property name = "url" value = "${jdbc.url}" />
<property name = "username" value = "${jdbc.username}" />
<property name = "password" value = "${jdbc.password}" />
</bean>
测试
5、JdbcTemplate 用法提升
5.1、queryForMap 返回一个 Map 集合
5.1.1、修改 ManagerDaoImpl.java
public Map findById1(int mid) {String sql="select * from manager where mid=?";
Map m=jdbcTemplate.queryForMap(sql,mid);
return m;
}
5.1.2、修改 STest.java
@Test
public void findById1(){Map m=managerService.findById1(5);
System.out.println(m);
}
5.2、queryForList 返回一个 List 集合
5.2.1、修改 ManagerDaoImpl.java
public List findById2(int n) {String sql="select * from manager where mid>?";
List list=jdbcTemplate.queryForList(sql,n);
return list;
}
5.2.2、修改 STest.java
@Test
public void findById2(){List list=managerService.findById2(5);
System.out.println(list);
}
5.3、RowMapper 返回自定义对象
5.3.1、修改 ManagerDaoImpl.java
public List findAll1() {String sql="select * from manager";
List list=jdbcTemplate.query(sql, new RowMapper() {public Object mapRow(ResultSet rs, int rowNum) throws SQLException {Manager m=new Manager();
m.setMid(rs.getInt("mid"));
m.setUname(rs.getString("uname"));
m.setPword(rs.getString("pword"));
m.setZcsj(rs.getDate("zcsj"));
return m;
}
});
return list;
}
5.3.2、修改 STest.java
@Test
public void findAll1(){List list=managerService.findAll1();
System.out.println(list);
}
6、继承 JdbcDaoSupport
6.1、JdbcDaoSupport 类
JdbcDaoSupport 是 spring 框架为我们提供的一个类,该类中定义了一个 JdbcTemplate 对象,我们可以直接获取使用,但是要想创建该对象,需要为其提供一个数据源。
6.2、新建 dao 实现类
ManagerDaoImpl1.java
import com.tyschool.spring007.javabean.Manager;
import com.tyschool.spring007.manager.dao.IManagerDao;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import java.util.List;
import java.util.Map;
public class ManagerDaoImpl1 extends JdbcDaoSupport implements IManagerDao {public List findAll() {String sql="select * from manager";
List<Manager> list=getJdbcTemplate().query(sql,new BeanPropertyRowMapper<Manager>(Manager.class));
return list;
}
public Manager findById(int mid) {return null;
}
public int updateManager(Manager m) {return 0;
}
public int addManager(Manager m) {return 0;
}
public int deleteManager(int mid) {return 0;
}
public List findByName(String name) {return null;
}
public int allCount() {return 0;
}
public Map findById1(int mid) {return null;
}
public List findById2(int n) {return null;
}
public List findAll1() {return null;
}
}
6.3、修改配置文件
<bean id="managerDaoImpl1" class="com.tyschool.spring007.manager.dao.impl.ManagerDaoImpl1">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="managerServiceImpl" class="com.tyschool.spring007.manager.service.impl.ManagerServiceImpl">
<property name="managerDao" ref="managerDaoImpl1"></property>
</bean>
测试
7、Spring 中事务控件
7.1、Spring 中的事务接口
在 spring 中为我们提供了一组事务控制的接口,我们可以直接使用来控制事务,要想使用事务控制接口就必须拥有 spring-tx.jar 的包。
在前面我们通过编程的方式实现了我们的事务,现在我们使用配置的方式来完成我们的事务。
7.2、PlatformTransactionManager 类
PlatformTransactionManager 类中有三个方法来操作事务:
getTransaction(TransactionDefinition definition)// 获取事务状态信息
commit(TransactionStatus status)// 提交事务
roolback(TransactionStatus status)// 回滚事务
在事务中我们实际管理的对象是:
org.springframework.jdbc.datasource.DataSourceTransactionManager———spring-jdbc\ibatis
org.springframework.orm.hibernate5.HibernateTransactionManager————hibernate
7.2.1、TransactionDefinition
事务定义信息对象,里面的方法有:
getName():事务对象名称
getIsolationLevel():事务隔离级别
getPropagationBehavior():事务传播行为
getTimeout():事务超时时间
isReadOnly():事务是否只读
事务状态:
读写型:增加、修改、删除操作
只读型:查询操作
事务隔离级别:
事务传播行为:
事务传播行为指的就是当一个事务方法被另一个事务方法调用时,这个事务方法应该如何进行。
required
@Transactional(propagation = Propagation.REQUIRED)
public void methodA() {methodB();
// do something
}
@Transactional(propagation = Propagation.REQUIRED)
public void methodB() {// do something
}
单独调用 methodB 方法时,因为当前上下文不存在事务,所以会开启一个新的事务。
调用 methodA 方法时,因为当前上下文不存在事务,所以会开启一个新的事务。当执行到 methodB 时,methodB 发现当前上下文有事务,因此就加入到当前事务中来。
supports
@Transactional(propagation = Propagation.REQUIRED)
public void methodA() {methodB();
// do something
}
// 事务属性为 SUPPORTS
@Transactional(propagation = Propagation.SUPPORTS)
public void methodB() {// do something
}
单纯的调用 methodB 时,methodB 方法是非事务的执行的。当调用 methdA 时,methodB 则加入了 methodA 的事务中, 事务地执行。
超时时间:
有的时候为了系统中关键部分的性能问题,它的事务执行时间应该尽可能的短。因此可以给这些事务设置超时时间,以秒为单位。默认值是 -1,没有超时限制。
事务是否只读:
如果后端数据库发现当前事务为只读事务,那么就会进行一系列的优化措施。因此,只有对于那些有可能启动一个新事务的传播行为(REQUIRED,REQUIRES_NEW,NESTED)的方法来说,才有意义。
7.2.2、TransactionStatus
事务对象的状态信息,方法有:
flush()// 刷新事务
hasSavepoint()// 获取是否存在的存储点
isCompleted()// 事务是否完成
isNewTransaction()// 获取事务是否为新事务
isRollbackOnly()// 获取事务是否回滚
setRollbackOnly()// 设置事务回滚
8、基于 XML 事务控制
8.1、修改配置头部信息
xmlns:context="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/aop"
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
8.2、配置事务管理器
<!-- 配置一个事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
8.3、配置事务
<!-- 事务配置 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager" ></tx:advice>
8.4、配置事务属性
<!-- 事务配置 -->
<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:attributes>
</tx:advice>
8.5、配置 AOP 切入点
<!-- 面向切面配置 -->
<aop:config>
<!-- 配置切入点 -->
<aop:pointcut id="pt1" expression="execution(* com.tyschool.spring007.manager.service.impl.*.*(..))"/>
</aop:config>
8.6、配置切入及通知
<!-- 面向切面配置 -->
<aop:config>
<!-- 配置切入点 -->
<aop:pointcut id="pt1" expression="execution(* com.tyschool.spring007.manager.service.impl.*.*(..))"/>
<!-- 通知与切入点表达式关系 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
</aop:config>
8.7、修改 ManagerDaoImpl1.java
public int updateManager(Manager m) {String sql="update manager set pword=? where mid=?";
getJdbcTemplate().update(sql,"1234567",5);
int n=1/0;
getJdbcTemplate().update(sql,"1234567",3);
return 0;
}
测试
9、基于注解事务控制(项目创建)
9.1、创建新项目
创建一个注解的项目 spring008
9.2、导包
<?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>com.tyschool</groupId>
<artifactId>spring008</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.13.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.2.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
</dependencies>
</project>
9.3、创建 javabean
package com.tyschool.spring008.javabean;
import java.io.Serializable;
import java.util.Date;
public class Manager implements Serializable {private int mid;
private String uname;
private String pword;
private Date zcsj;
public int getMid() {return mid;
}
public void setMid(int mid) {this.mid = mid;
}
public String getUname() {return uname;
}
public void setUname(String uname) {this.uname = uname;
}
public String getPword() {return pword;
}
public void setPword(String pword) {this.pword = pword;
}
public Date getZcsj() {return zcsj;
}
public void setZcsj(Date zcsj) {this.zcsj = zcsj;
}
@Override
public String toString() {return "Manager{" +
"mid=" + mid +
", uname='" + uname + '\'' +
", pword='" + pword + '\'' +
", zcsj=" + zcsj +
'}';
}
}
9.4、创建持久层与业务层
//IManagerDao.java
import com.tyschool.spring008.javabean.Manager;
public interface IManagerDao {public int updateManager(Manager m1, Manager m2);
}
//ManagerDaoImpl.java
import com.tyschool.spring008.javabean.Manager;
import com.tyschool.spring008.manager.dao.IManagerDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository("managerDaoImpl")
public class ManagerDaoImpl implements IManagerDao {@Autowired
@Qualifier("jdbcTemplate")
private JdbcTemplate jdbcTemplate;
public int updateManager(Manager m1, Manager m2) {String sql="update manager set pword=? where mid=?";
int n1=jdbcTemplate.update(sql,m1.getPword(),m1.getMid());
int n2=jdbcTemplate.update(sql,m2.getPword(),m2.getMid());
return 0;
}
}
//IManagerService.java
import com.tyschool.spring008.javabean.Manager;
public interface IManagerService {public int updateManager(Manager m1, Manager m2);
}
//ManagerServiceImpl.java
import com.tyschool.spring008.javabean.Manager;
import com.tyschool.spring008.manager.dao.IManagerDao;
import com.tyschool.spring008.manager.service.IManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Service("managerServiceImpl")
public class ManagerServiceImpl implements IManagerService {@Autowired
@Qualifier("managerDaoImpl")
IManagerDao managerDao;
public int updateManager(Manager m1, Manager m2) {return managerDao.updateManager(m1,m2);
}
}
9.5、配置 applicationContext.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"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--spring 创建对象时要扫描的包 -->
<context:component-scan base-package="com.tyschool.spring008"></context:component-scan>
</beans>
9.6、编写 Bean
db.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.1.123:3306/spring?serverTimezone=UTC
jdbc.username=root
jdbc.password=Root12345
DbUtilsC3P0.java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
@Component
@PropertySource(value={"classpath:db.properties"},ignoreResourceNotFound = false)
public class DbUtilsC3P0 {@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(name="dataSource")
public DataSource createDateSource(){DriverManagerDataSource cds=new DriverManagerDataSource();
cds.setDriverClassName(driver);
cds.setUrl(url);
cds.setUsername(username);
cds.setPassword(password);
return cds;
}
@Bean(name="jdbcTemplate")
public JdbcTemplate createJdbcTemplate(DataSource dataSource){return new JdbcTemplate(dataSource);
}
}
9.7、编写测试类
import com.tyschool.spring008.javabean.Manager;
import com.tyschool.spring008.manager.service.IManagerService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.Date;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value={"classpath:applicationContext.xml"})
public class STest {@Autowired
@Qualifier("managerServiceImpl")
IManagerService managerService;
@Test
public void updateManager(){Manager m1=new Manager();
m1.setMid(5);
m1.setUname("李四");
m1.setPword("lisi1");
m1.setZcsj(new Date());
Manager m2=new Manager();
m2.setMid(6);
m2.setUname("李四");
m2.setPword("lisi1");
m2.setZcsj(new Date());
managerService.updateManager(m1,m2);
}
}
10、基于注解事务控制(事务处理)
10.1、配置事务管理器
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
10.2、@Transactional 注解
修改 ManagerServiceImpl.java
import com.tyschool.spring008.javabean.Manager;
import com.tyschool.spring008.manager.dao.IManagerDao;
import com.tyschool.spring008.manager.service.IManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Service("managerServiceImpl")
@Transactional(readOnly=true,propagation= Propagation.SUPPORTS)
public class ManagerServiceImpl implements IManagerService {@Autowired
@Qualifier("managerDaoImpl")
IManagerDao managerDao;
@Transactional(readOnly = false,propagation = Propagation.REQUIRED)
public int updateManager(Manager m1, Manager m2) {return managerDao.updateManager(m1,m2);
}
}
注意:
@Transactional
出现接口上,表示该接口的所有实现类都有事务支持。
出现在类上,表示类中所有方法有事务支持
出现在方法上,表示方法有事务支持。
优先级:方法、类、接口
10.3、开启事务支持
<!-- 开启 spring 对注解事务的支持 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
测试
11、基于纯配置类事务控制
11.1、编写配置类
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Import;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@ComponentScan("com.tyschool.spring008")
@Import({DbUtilsC3P0.class})
@EnableTransactionManagement
public class SpringApplicationContext {
}
注意:
@EnableTransactionManagement
开启 spring 对注解事务的支持
11.2、修改 DbUtilsC3P0.java
@Bean(name="transactionManager")
public DataSourceTransactionManager createTransactionManager(DataSource dataSource){return new DataSourceTransactionManager(dataSource);
}
11.3、修改测试类
@ContextConfiguration(classes = com.tyschool.spring008.utils.SpringApplicationContext.class)
测试