1.为什么要使用Spring提供的jdbc封装
2.JdbcTemplate的增删改查
3.JdbcDaoSupport
4.转账案例
5.Spring对事物的支持
6.XML的事务配置
7.事务方法的属性
8.注解的事务配置
一、为什么要使用Spring提供的jdbc封装
小结:
1.使用Spring为我们提供的模板类以及基类可以简化开发.
2.不同的持久化技术,Spring提供了不同的模板类和基类.
二、JdbcTemplate的增删改查
1、数据库
2、添加依赖 新增 Spring-jdbc Spring-tx
<?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.xj</groupId>
<artifactId>Spring04</artifactId>
<version>1.0.0</version>
<properties>
<!--定义全局变量,变量名为:project.spring.version-->
<project.spring.version>5.0.0.RELEASE</project.spring.version>
</properties>
<dependencies>
<!--Spring-core-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${project.spring.version}</version>
</dependency>
<!--Spring-beans-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${project.spring.version}</version>
</dependency>
<!--Spring-test-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${project.spring.version}</version>
</dependency>
<!--Spring-expression-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${project.spring.version}</version>
</dependency>
<!--Spring-context-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${project.spring.version}</version>
</dependency>
<!--Spring-aop-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${project.spring.version}</version>
</dependency>
<!--新增 Spring-jdbc Spring-tx -->
<!--Spring-jdbc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${project.spring.version}</version>
</dependency>
<!--Spring-tx-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${project.spring.version}</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--德鲁伊连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<!--mysql连接驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.20</version>
</dependency>
<!-- aspectjweaverr -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.2</version>
</dependency>
</dependencies>
<build>
<!--从哪个地方加载配置文件-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
</project>
3、实体类
package com.xj.bean;
import lombok.*;
import java.math.BigDecimal;
import java.util.Date;
/**
* Created by Administrator on 2019/12/29 0029.
*/
@Setter@Getter@ToString
@NoArgsConstructor
@AllArgsConstructor
public class Employee {
private Integer id;
private String name;
private Integer age;
private Date hiredate;
private BigDecimal salary;
}
4、dao
package com.xj.dao;
import com.xj.bean.Employee;
import java.util.List;
/**
* Created by Administrator on 2019/12/29 0029.
*/
public interface IEmployeeDao {
void save(Employee employee);
void update(Employee employee);
void delete(Integer id);
List<Employee> list();
Employee get(Integer id);
}
package com.xj.dao.impl;
import com.xj.bean.Employee;
import com.xj.dao.IEmployeeDao;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
/**
* Created by Administrator on 2019/12/29 0029.
*/
public class EmployeeDaoImpl implements IEmployeeDao{
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource){
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public void save(Employee employee) {
this.jdbcTemplate.update(
"insert into employee (name,age,hiredate,salary) values(?,?,?,?)",
employee.getName(),employee.getAge(), employee.getHiredate(), employee.getSalary()
);
}
public void update(Employee employee) {
this.jdbcTemplate.update(
"update employee set name=?,age=?,hiredate=?,salary=? where id=?",
employee.getName(),employee.getAge(), employee.getHiredate(), employee.getSalary(), employee.getId()
);
}
public void delete(Integer id) {
this.jdbcTemplate.update(
"delete from employee where id=?",
id
);
}
public List<Employee> list() {
List<Employee> list = this.jdbcTemplate.query(
"select * from employee",
new RowMapper<Employee>() {
/*
* 方法的返回值,就会直接封装到集合中
* 第一个参数:结果集对象
* */
public Employee mapRow(ResultSet rs, int romNum) throws SQLException {
Employee employee = new Employee();
employee.setId(rs.getInt("id"));
employee.setName(rs.getString("name"));
employee.setAge(rs.getInt("age"));
employee.setHiredate(rs.getDate("hiredate"));
employee.setSalary(rs.getBigDecimal("salary"));
return employee;
}
}
);
return list;
}
public Employee get(Integer id) {
/* List<Employee> list = this.jdbcTemplate.query(
"select * from employee where id=?",
new Object[]{id},//数组 给sql语句赋值
new RowMapper<Employee>() {
public Employee mapRow(ResultSet rs, int romNum) throws SQLException {
Employee employee = new Employee();
employee.setId(rs.getInt("id"));
employee.setName(rs.getString("name"));
employee.setAge(rs.getInt("age"));
employee.setHiredate(rs.getDate("hiredate"));
employee.setSalary(rs.getBigDecimal("salary"));
return employee;
}
}
);
return list.size() > 0 ? list.get(0) : null;//如果查询的数据不存在,返回空
}*/
//如果查询的数据不存在,会报错
Employee employee = this.jdbcTemplate.queryForObject(
"select * from employee where id=?",
new Object[]{id},
new RowMapper<Employee>() {
public Employee mapRow(ResultSet rs, int romNum) throws SQLException {
Employee employee = new Employee();
employee.setId(rs.getInt("id"));
employee.setName(rs.getString("name"));
employee.setAge(rs.getInt("age"));
employee.setHiredate(rs.getDate("hiredate"));
employee.setSalary(rs.getBigDecimal("salary"));
return employee;
}
}
);
return employee;
}
}
5、配置文件
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring
jdbc.username=root
jdbc.password=root
<?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
http://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="db.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="dao" class="com.xj.dao.impl.EmployeeDaoImpl">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
6、测试类
package com.xj;
import com.xj.bean.Employee;
import com.xj.dao.IEmployeeDao;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
/**
* Created by Administrator on 2019/12/29 0029.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class App {
@Autowired
private IEmployeeDao dao;
@Test
public void testSave(){
Employee employee = new Employee(null,"rose",16,new Date(),new BigDecimal(1000));
dao.save(employee);
}
@Test
public void testUpdate(){
Employee employee = new Employee(1,"jack",16,new Date(),new BigDecimal(2000));
dao.update(employee);
}
@Test
public void testDelete(){
dao.delete(1);
}
@Test
public void testList(){
List<Employee> list = dao.list();
System.out.println(list);
}
@Test
public void testGet(){
Employee employee = dao.get(20);
System.out.println(employee);
}
}
三、JdbcDaoSupport
dao了只需继承JdbcDaoSupport,则继承了JdbcTemplate字段和DataSource属性
package com.xj.dao.impl;
import com.xj.bean.Employee;
import com.xj.dao.IEmployeeDao;
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;
/**
* Created by Administrator on 2019/12/29 0029.
*/
public class EmployeeDaoImpl extends JdbcDaoSupport implements IEmployeeDao{
/*private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource){
this.jdbcTemplate = new JdbcTemplate(dataSource);
}*/
public void save(Employee employee) {
super.getJdbcTemplate().update(
"insert into employee (name,age,hiredate,salary) values(?,?,?,?)",
employee.getName(),employee.getAge(), employee.getHiredate(), employee.getSalary()
);
}
public void update(Employee employee) {
super.getJdbcTemplate().update(
"update employee set name=?,age=?,hiredate=?,salary=? where id=?",
employee.getName(),employee.getAge(), employee.getHiredate(), employee.getSalary(), employee.getId()
);
}
public void delete(Integer id) {
super.getJdbcTemplate().update(
"delete from employee where id=?",
id
);
}
public List<Employee> list() {
List<Employee> list = super.getJdbcTemplate().query(
"select * from employee",
new RowMapper<Employee>() {
/*
* 方法的返回值,就会直接封装到集合中
* 第一个参数:结果集对象
* */
public Employee mapRow(ResultSet rs, int romNum) throws SQLException {
Employee employee = new Employee();
employee.setId(rs.getInt("id"));
employee.setName(rs.getString("name"));
employee.setAge(rs.getInt("age"));
employee.setHiredate(rs.getDate("hiredate"));
employee.setSalary(rs.getBigDecimal("salary"));
return employee;
}
}
);
return list;
}
public Employee get(Integer id) {
/* List<Employee> list = super.getJdbcTemplate().query(
"select * from employee where id=?",
new Object[]{id},
new RowMapper<Employee>() {
public Employee mapRow(ResultSet rs, int romNum) throws SQLException {
Employee employee = new Employee();
employee.setId(rs.getInt("id"));
employee.setName(rs.getString("name"));
employee.setAge(rs.getInt("age"));
employee.setHiredate(rs.getDate("hiredate"));
employee.setSalary(rs.getBigDecimal("salary"));
return employee;
}
}
);
return list.size() > 0 ? list.get(0) : null;//如果查询的数据不存在,返回空
}*/
//如果查询的数据不存在,会报错
Employee employee = super.getJdbcTemplate().queryForObject(
"select * from employee where id=?",
new Object[]{id},
new RowMapper<Employee>() {
public Employee mapRow(ResultSet rs, int romNum) throws SQLException {
Employee employee = new Employee();
employee.setId(rs.getInt("id"));
employee.setName(rs.getString("name"));
employee.setAge(rs.getInt("age"));
employee.setHiredate(rs.getDate("hiredate"));
employee.setSalary(rs.getBigDecimal("salary"));
return employee;
}
}
);
return employee;
}
}
四、转账案例
1、添加依赖,参考上面
2、数据库
3、实体类
package com.xj.bean;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* Created by Administrator on 2019/12/30 0030.
*/
@Setter@Getter@ToString
public class Account {
private Integer id;
private Integer balance;
}
4、dao
package com.xj.dao;
/**
* Created by Administrator on 2019/12/30 0030.
*/
public interface IAccountDao {
void transIn(Integer inId,Integer money);
void transOut(Integer OutId,Integer money);
}
package com.xj.dao.impl;
import com.xj.dao.IAccountDao;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
/**
* Created by Administrator on 2019/12/30 0030.
*/
public class AccountDaoImpl implements IAccountDao{
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource){
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public void transIn(Integer inId, Integer money) {
this.jdbcTemplate.update(
"update account set balance=balance+? where id=?",
money,inId
);
}
public void transOut(Integer OutId, Integer money) {
this.jdbcTemplate.update(
"update account set balance=balance-? where id=?",
money,OutId
);
}
}
5、service
package com.xj.service;
/**
* Created by Administrator on 2019/12/30 0030.
*/
public interface IAccountService {
void treans(Integer inID,Integer outId,Integer money);
}
package com.xj.service.impl;
import com.xj.dao.IAccountDao;
import com.xj.service.IAccountService;
import lombok.Setter;
/**
* Created by Administrator on 2019/12/30 0030.
*/
public class AccountServiceImpl implements IAccountService{
@Setter
private IAccountDao dao;
public void treans(Integer inId, Integer outId, Integer money) {
dao.transIn(inId,money);
dao.transOut(outId,money);
}
}
6、配制文件 db.properties参考上面
<?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
http://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="db.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="dao" class="com.xj.dao.impl.AccountDaoImpl">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="service" class="com.xj.service.impl.AccountServiceImpl">
<property name="dao" ref="dao"/>
</bean>
</beans>
7、测试类
package com.xj;
import com.xj.service.IAccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Created by Administrator on 2019/12/29 0029.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class App {
@Autowired
private IAccountService service;
@Test
public void testTrans(){
service.treans(1,2,1000);
}
}
五、Spring对事物的支持
在上面转账的案例中,如果没有事物,转账过程中出现了异常,如下图,那么转入的钱会增加,转出的钱并没有减少。造成数据不一致。
解决方法:使用Spring的事务管理
Spring的事务管理主要包括3个接口:
TransactionDefinition:封装事务的隔离级别,超时时间,是否为只读事务和事务的传播规则等事务属性,可通过XML配置具体信息。
PlatformTransactionManager:根据TransactionDefinition提供的事务属性配置信息,创建事务。
TransactionStatus:封装了事务的具体运行状态。比如,是否是新开启事务,是否已经提交事务,设置当前事务为rollback-only等。
Spring支持编程式事务管理和声明式事务管理:
编程式事务管理:事务和业务代码耦合度太高。
声明式事务管理:侵入性小,把事务从业务代码中抽离出来,提高维护性。XML/Annocation
Spring的事务管理:
1,PlatformTransactionManager:接口统一,抽取处理事务操作相关的方法;
1):TransactionStatus getTransaction(TransactionDefinition definition): 根据事务定义信息从事务环境中返回一个已存在的事务,或者创建一个新的事务,并用TransactionStatus描述该事务的状态。
2):void commit(TransactionStatus status): 根据事务的状态提交事务,如果事务状态已经标识为rollback-only,该方法执行回滚事务的操作。
3):void rollback(TransactionStatus status):将事务回滚,当commit方法抛出异常时,rollback会被隐式调用
2,在使用spring管理事务的时候,首先得告诉spring使用哪一个事务管理器;
常用的事务管理器: DataSourceTransactionManager:使用JDBC,MyBatis的事务管理器; HibernateTransactionManager:使用Hibernate的事务管理器;
六、XML的事务配置
在xml文件中添加事务配置
<!--事务管理器-->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置事务-->
<aop:config>
<!--配置切入点-->
<aop:pointcut id="txPointcut"
expression="execution( * com.xj.service.IAccountService.*(..))"/>
<!--配置切面-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"></aop:advisor>
</aop:config>
<!--事务增强器-->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="trans"/>
</tx:attributes>
</tx:advice>
注:记得添加aop命名空间
如果转账过程中没有出现异常,则转账成功。如果发生失败,则数据库中的数据不会发生改变。
七、事务方法的属性
事务方法属性:
1,name:匹配到的方法模式;
2,read-only:如果为true,开启一个只读事务,只读事务的性能较高,但是不能在只读事务中,使用DML;
3,isolation:代表数据库事务隔离级别(就使用默认) DEFAULT:让spring使用数据库默认的事务隔离级别; 其他:spring模拟;
4,no-rollback-for: 如果遇到的异常是匹配的异常类型,就不回滚事务;
5,rollback-for:如果遇到的异常是指定匹配的异常类型,才回滚事务;
spring默认情况下,spring只会去回滚RuntimeException及其子类,不会回滚Exception和Thowable.
6,propagation:事务的传播方式(当一个方法已经在一个开启的事务当中了,应该怎么处理自身的事务)
1,REQUIRED(默认的传播属性):如果当前方法运行在一个没有事务环境的情况下,则开启一个新的事务,如果当前方法运行在一个已经开启了的事务里面,把自己加入到开启的那个事务中
2,REQUIRES_NEW:不管当前方法是否运行在一个事务空间之内,都要开启自己的事务
通用的事务配置
<!--事务增强器-->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<!--查询方法时只读事务,非查询的方法时只读事务-->
<tx:method name="select*" read-only="true"/>
<tx:method name="find*" read-only="true"/>
<tx:method name="query*" read-only="true"/>
<tx:method name="get*" read-only="true"/>
<tx:method name="list*" read-only="true"/>
<tx:method name="*" />
</tx:attributes>
</tx:advice>
八、注解的事务配置
1、配置注解方式
<!--事务管理器-->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--事务的注解驱动-->
<tx:annotation-driven transaction-manager="txManager"></tx:annotation-driven>
</beans>
2、实现类上添加注解
注:如果想设置read-only,单独在方法上设置