事务&JDBC模板

f


前言

一:创建aop的步骤

1 导入包

2.引入配置文件

3:代码

增强类:有接口:spring底层会自动使用jdbc动态代理
增强类:没有接口:spring会采用cjlib动态代理

1.xml文件配置

<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"
	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/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
	http://www.springframework.org/schema/tx 
	http://www.springframework.org/schema/tx/spring-tx.xsd">

2.目标类


/**
 * 配置方法
 * @author 86139
 *
 */
public class OrderDao {
	public void add() {
		System.out.println("添加用户");
	}
	public void delete() {
		System.out.println("删除用户");
	}
	public void update() {
		System.out.println("更新用户");
	}
	public void find() {
		System.out.println("查找用户");
	}
}


3.切面类

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;


@Aspect  //注释切面类
public class MyAspectAnno {
	//配置增强方法 类似于xml文件的配置    直接进行配置 修改时要修改底层代码
	//<aop:pointcut expression="execution(* com.Demo01.ProductImpl.add(..))" id="pointcut1"/>
	@Before(value = "execution(* com.demo01.OrderDao.add(..))")		
	public void before() {
		System.out.println("前置增强");
	}
}

4测试类


/**
 * Spring 注解开发
 * @author 86139
 * 固定搭配
 @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
 
 	注入目标类 orderDao ,就可以调用OrderDao的方法
	@Resource(name = "orderDao")
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SpringDemo1 {
	
	@Resource(name = "orderDao")
	private OrderDao dao;
	@Test
	public void demo1() {
		dao.add();
		dao.delete();
		dao.update();
		dao.find();
		
	}
}

4.Spring的注解的AOP的通知类型

1.前置通知

@Before :
@Before(value = "execution(* com.demo01.OrderDao.add(..))")

2.后置通知

@AfterReturning

@AfterReturning(value = "execution(* com.demo01.OrderDao.add(..))")	

后置通知获取返回值
获取张三

public String delete() {
		System.out.println("删除用户");
		return "张三";
		
	}
	@AfterReturning(value = "execution(* com.demo01.OrderDao.delete(..))",
					returning = "result"		//Spring默认传递返回值返回值id
			)
	public void afterReturning(Object result) {				//名字必须对应上面的返回值id
		System.out.println("后置增强" + result);
	}

3.环绕通知

@Around

/**
	 * 环绕通知
	 * @throws Throwable 
	 *
	 */
	@Around(value = "execution(* com.demo01.OrderDao.update(..))")
	public Object Around(ProceedingJoinPoint joinPoint) throws Throwable {
		System.out.println("====环绕前====");
		Object proceed = joinPoint.proceed();  //表明执行增强类
		
		System.out.println("====环绕后====");
		return proceed;
		
		
	}

4.异常抛出

@AfterThrowing

@AfterThrowing(value = "execution(* com.demo01.OrderDao.find(..))")
	public void afterThrowing() {
		System.out.println("异常抛出");
	}

异常抛出获取异常返回值

	@AfterThrowing(value = "execution(* com.demo01.OrderDao.find(..))",throwing = "erro")
	public void afterThrowing(Throwable erro) {   //这个erro必须和上面的erro一样
		System.out.println("异常抛出" + erro.getMessage());
	}

5.最终通知

/**
	 * 最终通知
	 * 
	 */
	@After(value = "execution(* com.demo01.OrderDao.find(..))")
	public void after() {
		System.out.println("最终通知");
	}
}

6切入点通知

	@After(value = "com.demo01.MyAspectAnno.pointcut1()")
	public void after() {
		System.out.println("最终通知");
	}
	
	
	/**
	 * 切入点配置,仅在本方法内部使用
	 */
	//标记切入点方法 直接调用路径
	@Pointcut(value = "execution(* com.demo01.OrderDao.find(..))")
	private void pointcut1() {}
}

二:Spring的JDBC模板使用

1 Spring的JDBC的模板

Spring是EE开发的一站式的框架,有EE开发的每层的解决方案。Spring对持久层也提供了解决方案:ORM模块和JDBC的模板。
Spring提供了很多的模板用于简化开发:

1.JDBC模板的使用步骤

1.导包

在这里插入图片描述

2.原代码
@Test
	public void demo1() {
		//创建连接池
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
		dataSource.setUrl("jdbc:mysql:///spring4_day03");
		dataSource.setUsername("root");
		dataSource.setPassword("admin");
		//创建jdbc模板
		JdbcTemplate jdbcTemplate = new JdbcTemplate();
		jdbcTemplate.setDataSource(dataSource);
		jdbcTemplate.update("insert into account values (null,?,?)","李四",24);
	}
3.将里面的new对象交给Spring进行管理

spring4之前不需要引入aop的包,spring4之后要引入aop包

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"
	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/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
	http://www.springframework.org/schema/tx 
	http://www.springframework.org/schema/tx/spring-tx.xsd">
xml配置
	<!-- 只要是在原代码中需要new的代码都可以交给Spring进行管理 -->
	<!-- 将连接池交给spring管理 -->
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
	<!-- 属性注入 -->
		<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
		<property name="url" value="jdbc:mysql:///spring4_day03"/>
		<property name="username" value="root"/>
		<property name="password" value="admin"/>
	</bean> 
	
	<!-- 配置Spring的jdbc的模板 -->
	<bean id = "jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
	<!-- 将上面配置的属性进行赋值给DataSource -->
		<property name="dataSource" ref="dataSource"/>
	</bean>
调用
//固定搭配
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")

public class JDBCDemo2 {
	
	//将要使用的方法注入进来
	@Resource(name = "jdbcTemplate")
	//创建注入方法实例
	private JdbcTemplate jdbcTemplate;
	
	@Test
	public void demo2() {
	jdbcTemplate.update("insert into account values(null,?,?)","王五",25);
	}
4 .使用开源连接池连接数据库
1.DBCP的使用
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
				<!--  属性注入-->
		<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
		<property name="url" value="jdbc:mysql:///spring4_day03"/>
		<property name="username" value="root"/>
		<property name="password" value="admin"/>
	</bean>
	<!-- 配置Spring的jdbc的模板 -->
	<bean id = "jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
	<!-- 将上面配置的属性进行赋值给DataSource -->
		<property name="dataSource" ref="dataSource"/>
	</bean>
2.C3P0的使用

在这里插入图片描述

3.引入外部包

创建jdbc.properties
key= value(外部配置文件里面没有引号)


jdbc.driverClass = com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql"///spring4_day03
jdbc.user=root
jdbc.password=admin

xml文件进行
引用

<!-- 引入外部文件 -->
	 <context:property-placeholder location="classpath:jdbc.properties"/>

配置
在xml中${} 引入外部元素

<!-- c3p0连接池 -->
	<bean id = "dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="${jdbc.driverClass}"/>
		<property name="jdbcUrl" value="${jdbc.url}"/>
		<property name="user" value="${jdbc.user}"/>
		<property name="password" value="${jdbc.password}"></property>
	</bean>
5.使用C3po连接池进行增删改查操作
//固定搭配 


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")


public class JDBCDemo2 {
	 

	//将要使用的方法注入进来
	@Resource(name = "jdbcTemplate")
	//创建注入方法实例
	private JdbcTemplate jdbcTemplate;
	/**
	 * 增
	 */
	@Test
	public void demo1() {
	jdbcTemplate.update("insert into account values(null,?,?)","王宝强",150);
	}
	/**
	 * 删
	 */
	@Test
	public void demo2() {
		jdbcTemplate.update("delete from account where id = ?",8);
	}
	/**
	 * 改
	 */
	
	@Test
	public void demo3() {
		jdbcTemplate.update("update account set name = ?,money=? where id=?" ,"王马",110,10);
	}
	
	/**
	 * 查询
	 */
	@Test
	public void demo4() {													//返回的是一个字符
		String name = jdbcTemplate.queryForObject("select name from account where id =?", String.class, 10);
		System.out.println("name"  + name);
	}
	/**
	 * 统计返回个数
	 */
	@Test
	public void demo5() {													//返回的是一个字符
		Long count = jdbcTemplate.queryForObject("select count(*) from account", Long.class);
		System.out.println("name"  + count);
	}
	
查询返回一个或多个对象
一个对象
public void demo6(){
		Account account = jdbcTemplate.queryForObject("select * from account where id = ?", new MyRowMapper(), 10);
		System.out.println(account);
	}



class MyRowMapper implements RowMapper<Account>{

		@Override
		public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
			Account account = new Account();
			account.setId(rs.getInt("id"));
			account.setName(rs.getString("name"));
			account.setMoney(rs.getDouble("money"));
			return account;
		}
		
	}	
多个对象
@Test
	public void demo7() {
		List<Account> list = jdbcTemplate.query("select * from account", new YourRowMapper());
		for (Account account : list) {
			System.out.println(account);
		}
	}






class YourRowMapper implements RowMapper<Account>{

		@Override						//结果集    //行号
		public Account mapRow(ResultSet rs, int num) throws SQLException {
			Account account = new Account();
			account.setId(rs.getInt("id"));
			account.setMoney(rs.getDouble("money"));
			account.setName(rs.getString("name"));
			return account;
		}
		
	}

三:事务的回顾

1:什么事务

事务:逻辑上的一组操作,组成这组操作的各个单元,要么全都成功,要么全都失败。

1:事务的特性

原子性:事务不可分割
一致性:事务执行前后数据完整性保持一致

隔离性:一个事务的执行不应该受到其他事务的干扰
持久性:一旦事务结束,数据就持久化到数据库

2:如果不考虑隔离性引发安全性问题

读问题
脏读		:一个事务读到另一个事务未提交的数据
不可重复读	:一个事务读到另一个事务已经提交的update的数据,导致一个事务中多次查询结果不一致
虚读、幻读	:一个事务读到另一个事务已经提交的insert的数据,导致一个事务中多次查询结果不一致。
写问题
丢失更新

3:解决读问题

设置事务的隔离级别
Read uncommitted	:未提交读,任何读问题解决不了。
Read committed	:已提交读,解决脏读,但是不可重复读和虚读有可能发生。
Repeatable read	:重复读,解决脏读和不可重复读,但是虚读有可能发生。
Serializable		:解决所有读问题。

2:Spring的事务管理的API

1:PlatformTransactionManager:平台事务管理器

平台事务管理器:接口,是Spring用于管理事务的真正的对象。
DataSourceTransactionManager	:底层使用JDBC管理事务
HibernateTransactionManager	:底层使用Hibernate管理事务

2:TransactionDefinition :事务定义信息

事务定义:用于定义事务的相关的信息,隔离级别、超时信息、传播行为、是否只读

3:TransactionStatus:事务的状态

事务状态:用于记录在事务管理过程中,事务的状态的对象。

4:事务管理的API的关系:

Spring进行事务管理的时候,首先平台事务管理器根据事务定义信息进行事务的管理,在事务管理过程中,产生各种状态,将这些状态的信息记录到事务状态的对象中。

3:Spring的事务的传播行为

1:Spring的传播行为

Spring中提供了七种事务的传播行为:
保证多个操作在同一个事务中
PROPAGATION_REQUIRED		:默认值,如果A中有事务,使用A中的事务,如果A没有,创建一个新的事务,将操作包含进来
PROPAGATION_SUPPORTS		:支持事务,如果A中有事务,使用A中的事务。如果A没有事务,不使用事务。
PROPAGATION_MANDATORY	:如果A中有事务,使用A中的事务。如果A没有事务,抛出异常。

保证多个操作不在同一个事务中
PROPAGATION_REQUIRES_NEW		:如果A中有事务,将A的事务挂起(暂停),创建新事务,只包含自身操作。如果A中没有事务,创建一个新事务,包含自身操作。
PROPAGATION_NOT_SUPPORTED	:如果A中有事务,将A的事务挂起。不使用事务管理。
PROPAGATION_NEVER				:如果A中有事务,报异常。

嵌套式事务
PROPAGATION_NESTED			:嵌套事务,如果A中有事务,按照A的事务执行,执行完成后,设置一个保存点,执行B中的操作,如果没有异常,执行通过,如果有异常,可以选择回滚到最初始位置,也可以回滚到保存点。

4.创建事务

1.创建service和dao

public interface AccountService {
	/**
	 * 
	 * @param from  转出人
	 * @param to    转入人
	 * @param money	转出金额
	 */
	public void transfer(String from,String to,Double money);
}






public interface AccountDao {
	/**
	 * 
	 * @param from		转出人
	 * @param money
	 */
	public void outMoney(String from,Double money);
	/**
	 * 
	 * @param to		转入人
	 * @param money
	 */
	public void inMoney(String to,Double money);
}

2.创建各自的实现类

public class AccountServiceImpl implements AccountService{
	//注入dao
	private AccountDao accountDao;
	//调用父类引用指向子类对象
	public void setAccountDao(AccountDao accountDao) {
		this.accountDao = accountDao;
	}
	public void transfer(String from, String to, Double money) {
		accountDao.outMoney(from, money);		//设置减少money
		accountDao.inMoney(to, money);			//设置增加money       共用money属性
		
	}






public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao{
	/*

	 * private JdbcTemplate JdbcTemplate;
	 * public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { JdbcTemplate =
	 * jdbcTemplate; }
	 */  
	@Override
	public void outMoney(String from, Double money) {
		// TODO Auto-generated method stub
		this.getJdbcTemplate().update("update account set money = money - ? where name = ?", money,from);
	}

	@Override
	public void inMoney(String to, Double money) {
		// TODO Auto-generated method stub
		this.getJdbcTemplate().update("update account set money = money + ? where name = ?",money,to);
	}

}




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"
	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/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
	http://www.springframework.org/schema/tx 
	http://www.springframework.org/schema/tx/spring-tx.xsd">
	
	<!-- 配置service -->
	<bean id="accountService" class="com.tx.demo.AccountServiceImpl">
		<property name="accountDao" ref="accountDao"/>
	</bean>

	<!-- 配置dao -->
	<bean id="accountDao" class="com.tx.demo.AccountDaoImpl">
		<property name="jdbcTemplate" ref="jdbcTemplate"/>
	</bean>
	
	<!-- 引入外部文件 -->
	<context:property-placeholder location="classpath:jdbc.properties"/>
	
	<!-- C3P0连接池 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="${jdbc.driverClass}"/>
		<property name="jdbcUrl" value="${jdbc.url}"/>
		<property name="user" value="${jdbc.user}"/>
		<property name="password" value="${jdbc.password}"/>
	</bean>
	
	<!-- 配置Spring的jdbc的模板 -->
	<bean id = "jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<!-- 将上面配置的属性进行赋值给DataSource -->
		<property name="dataSource" ref="dataSource"/>
	</bean>
</beans>

在没有事务处理的时候会出现脏读,不可重复度,虚读

所以要设置事务管理

xml方式的声明事务

1.配置事务管理器
2.配置事务增强
…propagation的方法有七种
3.aop的配置
xml配置是设置切入点,需要用到aop的jar包,



<!-- 配置事务管理器 -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<!-- 注入dataSource -->
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	<!-- 配置事务增强 -->					<!--给一个事务管理器 -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
				<!--name可以用*来表示所以方法    save*表示以save开头的所有的方法 -->
			<tx:method name="transfer" propagation="REQUIRED"/>
		</tx:attributes>
	</tx:advice>
	
	<!-- aop的设置-->
	<aop:config>
		<aop:pointcut expression="execution(* com.tx.demo.AccountServiceImpl.transfer(..))" id="pointcut1"/>
		<aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut1"/>
	</aop:config>
注解开发方式的事务声明

 第1步:配置事务管理器
在这里插入图片描述

 第2步:开启注解事务
在这里插入图片描述

 第3步:在业务层添加注解

在这里插入图片描述

总结

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值