Spring Three

插入小知识点(鸡翅)

spring配置文件分包引入(有注解就无关紧要了)

在这里插入图片描述

第1章 Spring中的JdbcTemplate

1.1 JdbcTemplate概述

它是spring框架中提供的一个对象,是对原始Jdbc API对象的简单封装。spring框架为我们提供了很多的操作模板类,入下图所示:
在这里插入图片描述
在spring-jdbc-4.24.RELEASE.jar中,我们在导包的时候,除了要导入这个jar包外,还需要导入一个spring-tx-4.2.4.RELEASE.jar(它是和事务相关的)。

1.2 JdbcTemplate对象的创建

我们可以参考它的源码,来一探究竟:
	public JdbcTemplate() {
	}

	public JdbcTemplate(DataSource dataSource) {
		setDataSource(dataSource);
		afterPropertiesSet();
	}

	public JdbcTemplate(DataSource dataSource, boolean lazyInit) {
		setDataSource(dataSource);
		setLazyInit(lazyInit);
		afterPropertiesSet();
	}

除了默认构造函数之外,都需要提供一个数据源。既然有set方法,依据我们之前学过的依赖注入,我们可不可以在配置文件中配置呢?
答案是肯定的。
1.3 spring中配置数据源
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

1.3.3.3 配置spring内置数据源

spring框架也提供了一个内置数据源,我们也可以使用spring的内置数据源,它就在spring-jdbc-4.2.4.REEASE.jar包中:

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
	<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
	<property name="url" value="jdbc:mysql:///spring_day04"></property>
	<property name="username" value="root"></property>
	<property name="password" value="1234"></property>
</bean>
1.3.4 将数据库连接的信息配置到属性文件中:
【定义属性文件】
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///spring_day02
jdbc.username=root
jdbc.password=123
【引入外部的属性文件】
一种方式:
    <!-- 引入外部属性文件: -->
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    	<property name="location" value="classpath:jdbc.properties"/>
    </bean>

二种方式:
<context:property-placeholder location="classpath:jdbc.properties"/>
1.4 JdbcTemplate的增删改查操作
1.4.1 前期准备
<?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">

	<!-- 配置一个数据库的操作模板:JdbcTemplate -->
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	
	<!-- 配置数据源 -->
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
	<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
	<property name="url" value="jdbc:mysql:///spring_day04"></property>
	<property name="username" value="root"></property>
	<property name="password" value="1234"></property>
</bean>
</beans>
创建数据库:
create database spring_day04;
use spring_day04;
创建表:
create table account(
	id int primary key auto_increment,
	name varchar(40),
	money float
)character set utf8 collate utf8_general_ci;
1.4.2 在spring配置文件中配置JdbcTemplate
1.4.3 最基本使用
public class JdbcTemplateDemo2 {
	public static void main(String[] args) {
		//1.获取Spring容器
		ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
		//2.根据id获取bean对象
		JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
		//3.执行操作
		jt.execute("insert into account(name,money)values('eee',500)");
	}
}
1.4.4 保存操作
public class JdbcTemplateDemo3 {
	public static void main(String[] args) {

		//1.获取Spring容器
		ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
		//2.根据id获取bean对象
		JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
		//3.执行操作
		//保存
		jt.update("insert into account(name,money)values(?,?)","fff",5000);
	}
}
1.4.5 更新操作
public class JdbcTemplateDemo3 {
	public static void main(String[] args) {

		//1.获取Spring容器
		ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
		//2.根据id获取bean对象
		JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
		//3.执行操作
		//修改
		jt.update("update account set money = money-? where id = ?",300,6);
	}
}
1.4.6 删除操作
public class JdbcTemplateDemo3 {
	public static void main(String[] args) {

		//1.获取Spring容器
		ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
		//2.根据id获取bean对象
		JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
		//3.执行操作
		//删除
		jt.update("delete from account where id = ?",6);
	}
}
1.4.7 查询所有操作
public class JdbcTemplateDemo3 {
	public static void main(String[] args) {

		//1.获取Spring容器
		ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
		//2.根据id获取bean对象
		JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
		//3.执行操作
		//查询所有
		List<Account> accounts = jt.query("select * from account where money > ? ", 
											new AccountRowMapper(), 500);
		for(Account o : accounts){
			System.out.println(o);
		}
	}
}

public class AccountRowMapper 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.getFloat("money"));
		return account;
	}
	
}

1.4.8 查询一个操作
使用RowMapper的方式:常用的方式
public class JdbcTemplateDemo3 {
	public static void main(String[] args) {

		//1.获取Spring容器
		ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
		//2.根据id获取bean对象
		JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
		//3.执行操作
		//查询一个
		List<Account> as = jt.query("select * from account where id = ? ", 
										new AccountRowMapper(), 55);
		System.out.println(as.isEmpty()?"没有结果":as.get(0));
	}
}

使用ResultSetExtractor的方式:不常用的方式
public class JdbcTemplateDemo3 {
	public static void main(String[] args) {

		//1.获取Spring容器
		ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
		//2.根据id获取bean对象
		JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
		//3.执行操作
		//查询一个
		Account account = jt.query("select * from account where id = ?",
									new AccountResultSetExtractor(),3);
		System.out.println(account);
	}
}

1.4.9 查询返回一行一列操作

public class JdbcTemplateDemo3 {
	public static void main(String[] args) {

		//1.获取Spring容器
		ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
		//2.根据id获取bean对象
		JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
		//3.执行操作
		//查询返回一行一列:使用聚合函数,在不使用group by字句时,都是返回一行一列。最长用的就是分页中获取总记录条数
		Integer total = jt.queryForObject("select count(*) from account where money > ? ",Integer.class,500);
		System.out.println(total);
	}
}
1.5 在dao中使用JdbcTemplate
1.5.1 准备实体类
/**
 * 账户的实体
 */
public class Account implements Serializable {

	private Integer id;
	private String name;
	private Float money;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Float getMoney() {
		return money;
	}
	public void setMoney(Float money) {
		this.money = money;
	}
	@Override
	public String toString() {
		return "Account [id=" + id + ", name=" + name + ", money=" + money + "]";
	}
}
1.5.2 第一种方式:在dao中定义JdbcTemplate
/**
 * 账户的接口
 */
public interface IAccountDao {
	
	/**
	 * 根据id查询账户信息
	 * @param id
	 * @return
	 */
	Account findAccountById(Integer id);

	/**
	 * 根据名称查询账户信息
	 * @return
	 */
	Account findAccountByName(String name);
	
	/**
	 * 更新账户信息
	 * @param account
	 */
	void updateAccount(Account account);
}

/**
 * 账户的持久层实现类
 * 此版本的dao,需要给dao注入JdbcTemplate
 */
public class AccountDaoImpl implements IAccountDao {

	private JdbcTemplate jdbcTemplate;
	
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	@Override
	public Account findAccountById(Integer id) {
		List<Account> list =  jdbcTemplate.query("select * from account where id = ? ",new AccountRowMapper(),id);
		return list.isEmpty()?null:list.get(0);
	}

	@Override
	public Account findAccountByName(String name) {
		List<Account> list =  jdbcTemplate.query("select * from account where name = ? ",new AccountRowMapper(),name);
		if(list.isEmpty()){
			return null;
		}
		if(list.size()>1){
			throw new RuntimeException("结果集不唯一,不是只有一个账户对象");
		}
		return list.get(0);
	}

	@Override
	public void updateAccount(Account account) {
		jdbcTemplate.update("update account set money = ? where id = ? ",account.getMoney(),account.getId());
	}

}

配置文件
<?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">
	
	<!-- 配置一个dao -->
	<bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
		<!-- 注入jdbcTemplate -->
		<property name="jdbcTemplate" ref="jdbcTemplate"></property>
	</bean>
	
	<!-- 配置一个数据库的操作模板:JdbcTemplate -->
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	
	<!-- 配置数据源 -->
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
		<property name="url" value="jdbc:mysql:///spring_day04"></property>
		<property name="username" value="root"></property>
		<property name="password" value="1234"></property>
	</bean>
</beans>
思考:
	此种方式有什么问题吗?
答案:
	有个小问题。就是我们的dao有很多时,每个dao都有一些重复性的代码。下面就是重复代码:
	private JdbcTemplate jdbcTemplate;
	
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
能不能把它抽取出来呢?
请看下一小节。
1.5.3 第二种方式:让dao继承JdbcDaoSupport

JdbcDaoSupport是spring框架为我们提供的一个类,该类中定义了一个JdbcTemplate对象,我们可以直接获取使用,但是要想创建该对象,需要为其提供一个数据源:具体源码如下:
public abstract class JdbcDaoSupport extends DaoSupport {
//定义对象
private JdbcTemplate jdbcTemplate;
//set方法注入数据源,判断是否注入了,注入了就创建JdbcTemplate
public final void setDataSource(DataSource dataSource) {
if (this.jdbcTemplate == null || dataSource != this.jdbcTemplate.getDataSource()) { //如果提供了数据源就创建JdbcTemplate
this.jdbcTemplate = createJdbcTemplate(dataSource);
initTemplateConfig();
}
}
//使用数据源创建JdcbTemplate
protected JdbcTemplate createJdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}

//当然,我们也可以通过注入JdbcTemplate对象
public final void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
	this.jdbcTemplate = jdbcTemplate;
	initTemplateConfig();
}
//使用getJdbcTmeplate方法获取操作模板对象
public final JdbcTemplate getJdbcTemplate() {
  return this.jdbcTemplate;
}
/**
 * 账户的接口
 */
public interface IAccountDao {
	
	/**
	 * 根据id查询账户信息
	 * @param id
	 * @return
	 */
	Account findAccountById(Integer id);

	/**
	 * 根据名称查询账户信息
	 * @return
	 */
	Account findAccountByName(String name);
	
	/**
	 * 更新账户信息
	 * @param account
	 */
	void updateAccount(Account account);
}

/**
 * 账户的持久层实现类
 * 此版本dao,只需要给它的父类注入一个数据源
 */
public class AccountDaoImpl2 extends JdbcDaoSupport implements IAccountDao {

	@Override
	public Account findAccountById(Integer id) {
		//getJdbcTemplate()方法是从父类上继承下来的。
		List<Account> list = getJdbcTemplate().query("select * from account where id = ? ",new AccountRowMapper(),id);
		return list.isEmpty()?null:list.get(0);
	}

	@Override
	public Account findAccountByName(String name) {
		//getJdbcTemplate()方法是从父类上继承下来的。
		List<Account> list =  getJdbcTemplate().query("select * from account where name = ? ",new AccountRowMapper(),name);
		if(list.isEmpty()){
			return null;
		}
		if(list.size()>1){
			throw new RuntimeException("结果集不唯一,不是只有一个账户对象");
		}
		return list.get(0);
	}

	@Override
	public void updateAccount(Account account) {
		//getJdbcTemplate()方法是从父类上继承下来的。
		getJdbcTemplate().update("update account set money = ? where id = ? ",account.getMoney(),account.getId());
	}
}
配置文件:
<?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">
	
<!-- 配置dao2 -->
<bean id="accountDao2" class="com.itheima.dao.impl.AccountDaoImpl2">
	<!-- 注入dataSource -->
	<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
	<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
	<property name="url" value="jdbc:mysql:///spring_day04"></property>
		<property name="username" value="root"></property>
		<property name="password" value="1234"></property>
	</bean>
</beans>

思考:
两版Dao有什么区别呢?
答案:
第一种在Dao类中定义JdbcTemplate的方式,适用于所有配置方式(xml和注解都可以)。
第二种让Dao继承JdbcDaoSupport的方式,只能用于基于XML的方式,注解用不了。

会议事务

事务控制 【重点】
1. 什么是事务?
事务是用户操作数据库的基本单元。也可以说一个业务操作对应数据库就是一个事务操作。
2. JDBC中的事务
2.1 一条SQL命令执行完毕自动提交事务。
2.2 手动控制事务:
① conn.setAutoCommit(false);
② conn.commit() / conn.rollback();
2.3 管理事务的对象: connection对象 。
3. Mybatis中事务控制: 需要手动提交,否则会进行自动回滚 。
4. Spring中的事务控制
4.1 Spring采取声明式事务管理机制。程序员使用Spring框架开发时,只需要按照Spring的规范和约定在配置文件中去声明配置自己管理事务的形式即可, Spring框架会根据您的配置自动帮助您完成事务的管理控制。
4.2 管理事务的对象:
DataSourceTransactionManager – 依赖于数据源对象 dataSource

 事务的属性 
		5.1 传播性 : 主要是控制业务功能在相互调用的时候事务如何进行控制。
			① PROPAGATION_REQUIRED【默认】: 一定有事务。如果外层有事务,则加入外层的事务中运行。如果外层没有事务,会创建一个新的事务运行。
			主要用于增、删、改操作。
			② PROPAGATION_SUPPORTS: 支持事务。如果外层有事务,加入外层的事务。如果外层没有事务,不会创建事务。 
			主要用于查询操作。
			③ PROPAGATION_REQUIRES_NEW: 不管什么时候一定创建一个独立的事务。	
			④ PROPAGATION_NOT_SUPPORTED: 不支持事务。 外层有事务,我也不会加入,我自己也不会创建事务。 外层没有事务,我还是没有事务,也不会创建。
			⑤ PROPAGATION_NEVER : 一定不能运行在事务环境。 有事务则抛出异常。 
			⑥ PROPAGATION_MANDATORY : 一定得运行在事务环境。	没有事务就抛出异常。	

		5.2 隔离性 【面试点】
			名词解释:	
				-脏读:强调的是在多事务操作的环境下,一个事务读取到了另一个事务没有提交的数据。
				-不可重复读:强调的是在一个事务中针对一条数据的两次读取,结果不一致。
				-幻影读: 强调的是在一个事务中针对于一张表进行的两次统计结果不一致。
			事务的隔离级别:
				① 读未提交 read uncomitted
					- 会存在问题: 脏读、不可重复读、幻影读 
					- 安全性: 极差
					- 效率: 最高 
				② 读提交  read committed 
					- 会存在问题: 不可重复读、幻影读
					- 解决问题: 脏读
					- 安全性:一般
					- 效率: 较高
				③ 可重复读 repeatable read : 当一个事务在操作某一条数据的时候, 会将当前行数据加锁,事务结束后释放锁。
					- 会存在问题: 幻影读
					- 解决了问题: 脏读、不可重复读
					- 安全性: 较高
					- 效率: 较差
				
				④ 序列化读  serializable:当一个事务在对一张表进行操作的时候, 会将当前的表进行加锁,事务结束后释放锁。
					- 解决了问题: 脏读、不可重复读、幻影读
					- 安全性: 最高
					- 效率: 极差
		PS: Oracle数据库默认隔离级别为读提交。
			  Spring框架默认是采用当前数据库的隔离级别。
		5.3 回滚性:
			① Spring默认在程序抛出运行时异常后,事务做回滚处理。默认抛出非运行时异常,事务做提交处理。
			② 自定义事务的回滚性:

在这里插入图片描述

	PS: 对于事务的回滚性,我们采用Spring默认的设置即可。 
		5.4 只读性 : 当事务设置为只读性后,当前事务内不允许执行写操作。 (只读性oracle不支持,mysql支持)
		5.5 超时性 : 是指一个事务的执行时间的限制,超过这个时间则抛出异常。 (采用默认的即可,默认Spring是依据数据库默认的事务超时时间)

事务:DB最小执行单元。
	  多用户并发
	
	accounts
	id  name   balance
	1  zs   2000
一、多用户并发时 可能会产生的错误现象(问题)
1、脏读:  B事务 读到了 A事务 尚未提交的数据。
	   A                    B
	                   select balance
				       from accounts 
				       where id=1  --2000
	update accounts
	set balance=500
	where id=1
	...                 
	                   select balance
				       from accounts 
				       where id=1  --500
	...
	commit;
	
	事务的隔离isolation级别:  READ_COMMITTED   已提交读
		注意:这是Oracle的默认隔离级别。
		
2、不可重复读:A事务 在B事务的 两次查询过程中 修改了数据并提交,而导致B事务两次查到的数据不一致。
	   A                          B
	                   select balance
				       from accounts 
				       where id=1  --2000
	update accounts
	set balance=500
	where id=1
	...
	commit; 
	                   select balance
				       from accounts 
				       where id=1  --500
	解决方案:隔离级别  REPEATABLE_READ   可重复读
	注意:1) 这是mysql的默认隔离级别
		2) oracle不支持该级别
		3) oracle提供的解决方案为:
			select ... from ... for update --对查询出来的结果行  添加行级锁标记
			select ... from ... for update wait n --对查询出来的结果行  添加行级锁标记,等待n秒
			select ... from ... for update nowait --对查询出来的结果行  添加行级锁标记,不等待
3、幻读:A事务 在B事务的两次查询过程中 插入了数据并进行了提交 导致B事务 两次查询到的数据条目不一致。
         A                      B
		                   select count(*)
						   from accounts --1
	insert into...
	..
	commit;
		                   select count(*)
						   from accounts --2
	解决方案:隔离级别  SERIALIZABLE   序列化/串行操作
	注意:这是DB的最高隔离级别,一旦设置 等效只能一个client操作数据库。
			慎重使用!!
			
隔离级别:4种
	read_uncommitted   未提交读
	read_committed     已提交读
	repeatable_read    可重复读
	serializable       串行读
	
隔离性:解决 多用户并发操作数据库时 可以会带来的数据相互影响。

二、传播性
	解决 事务嵌套时 存在的问题。
	
	Service1  insert1 select1
	Serivce2  delete2 update2
	MyService                                                 required
		m1(){      m1-tx begin
			s1.insert1();   s1-tx  begin   end   ok    ok     加入m1-tx
			s2.delete2();   s2-tx   begin   end  ok    err    加入m1-tx
			s1.select1();                        ok           加入m1-tx
			s2.update2();   s2-tx  begin   end   ok           加入m1-tx
		}          m1-tx end                     ok    err
		
		
	传播性propagation: REQUIRED  需要事务(外部有事务则加入;没有事务 则开启新事务)     增删改方法
	                   SUPPORTS  支持事务(外部有事务则加入;没有事务 则不开启新事务)   查询方法

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

Spring中的事务控制

2.1 Spring事务控制我们要明确的

第一:
JavaEE体系进行分层开发,事务处理位于业务层,Spring提供了分层设计业务层的事务处理解决方案。
第二:
spring框架为我们提供了一组事务控制的接口。具体在后面的第二小节介绍。这组接口是在spring-tx-4.2.4.RELEASE.jar中。
第三:
spring的事务控制都是基于AOP的,它既可以使用编程的方式实现,也可以使用配置的方式实现。我们学习的重点是使用配置的方式实现。

2.2.1 PlatformTransactionManager

此接口是spring的事务管理器,它里面提供了我们常用的操作事务的方法,如下图:
在这里插入图片描述
我们在开发中都是使用它的实现类,如下图:
在这里插入图片描述

真正管理事务的对象

org.springframework.jdbc.datasource.DataSourceTransactionManager 使用Spring JDBC或iBatis 进行持久化数据时使用
org.springframework.orm.hibernate3.HibernateTransactionManager 使用Hibernate版本进行持久化数据时使用

2.2.2 TransactionDefinition

它是事务的定义信息对象,里面有如下方法:
在这里插入图片描述

2.2.2.1 事务的隔离级别

在这里插入图片描述

2.2.2.2 事务的传播行为

REQUIRED:如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。一般的选择(默认值)
SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行(没有事务)
MANDATORY:使用当前的事务,如果当前没有事务,就抛出异常
REQUERS_NEW:新建事务,如果当前在事务中,把当前事务挂起。
NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起
NEVER:以非事务方式运行,如果当前存在事务,抛出异常
NESTED:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行REQUIRED类似的操作。

2.2.2.3 超时时间

默认值是-1,没有超时限制。如果有,以秒为单位进行设置。

2.2.2.4 是否是只读事务

建议查询时设置为只读。

2.2.3 TransactionStatus

此接口提供的是事务具体的运行状态,方法介绍如下图:
在这里插入图片描述

总结

在这里插入图片描述

2.3 基于XML的声明式事务控制(配置方式)重点

2.3.1 环境搭建

在这里插入图片描述

2.3.1.2 第二步:创建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
        		http://www.springframework.org/schema/aop 
        		http://www.springframework.org/schema/aop/spring-aop.xsd">	
</beans>
2.3.1.3 第三步:准备数据库表和实体类
2.3.1.6	第六步:在配置文件中配置业务层和持久层对
<!-- 配置service -->
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
	<property name="accountDao" ref="accountDao"></property>
</bean>
	
<!-- 配置dao -->
<bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
	<!-- 注入dataSource -->
	<property name="dataSource" ref="dataSource"></property>
</bean>
	
<!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
	<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
	<property name="url" value="jdbc:mysql:///spring_day04"></property>
	<property name="username" value="root"></property>
	<property name="password" value="1234"></property>
</bean>
2.3.2	配置步骤
2.3.2.1	第一步:配置事务管理器
<!-- 配置一个事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
	<!-- 注入DataSource -->
	<property name="dataSource" ref="dataSource"></property>
</bean>
2.3.2.2	第二步:配置事务的通知引用事务管理器
<!-- 事务的配置 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
</tx:advice>
2.3.2.3	第三步:配置事务的属性
<!--在tx:advice标签内部 配置事务的属性 -->
<tx:attributes>
<!-- 指定方法名称:是业务核心方法 
	read-only:是否是只读事务。默认false,不只读。
	isolation:指定事务的隔离级别。默认值是使用数据库的默认隔离级别。 
	propagation:指定事务的传播行为。
	timeout:指定超时时间。默认值为:-1。永不超时。
	rollback-for:用于指定一个异常,当执行产生该异常时,事务回滚。产生其他异常,事务不回滚。没有默认值,任何异常都回滚。
	no-rollback-for:用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时,事务回滚。没有默认值,任何异常都回滚。
	-->
	<tx:method name="*" read-only="false" propagation="REQUIRED"/>
	<tx:method name="find*" read-only="true" propagation="SUPPORTS"/>
</tx:attributes>
2.3.2.4	第四步:配置AOP-切入点表达式
<!-- 配置aop -->
<aop:config>
	<!-- 配置切入点表达式 -->
	<aop:pointcut expression="execution(* com.itheima.service.impl.*.*(..))" id="pt1"/>
</aop:config>
2.3.2.5	第五步:配置切入点表达式和事务通知的对应关系
<!-- 在aop:config标签内部:建立事务的通知和切入点表达式的关系 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>

2.4 基于XML和注解组合使用的整合方式

1.环境搭建

在这里插入图片描述

2.4.1.2	第二步:创建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"
        	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/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
        			http://www.springframework.org/schema/context
        		http://www.springframework.org/schema/context/spring-context.xsd">
	<!-- 配置spring要扫描的包 -->
    <context:component-scan base-package="com.itheima"></context:component-scan>
</beans>
2.4.1.3	第三步:创建数据库表和实体类
和基于xml的配置相同。略
2.4.1.4	第四步:创建业务层接口和实现类并使用注解让spring管理
业务层接口和基于xml配置的时候相同。略

/**
 * 账户的业务层实现类
 */
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
	@Autowired
	private IAccountDao accountDao;

	@Override
	public Account findAccountById(Integer id) {
		return accountDao.findAccountById(id);
	}

	@Override
	public void transfer(String sourceName, String targeName, Float money) {
		//1.根据名称查询两个账户
		Account source = accountDao.findAccountByName(sourceName);
		Account target = accountDao.findAccountByName(targeName);
		//2.修改两个账户的金额
		source.setMoney(source.getMoney()-money);//转出账户减钱
		target.setMoney(target.getMoney()+money);//转入账户加钱
		//3.更新两个账户
		accountDao.updateAccount(source);
		int i=1/0;
		accountDao.updateAccount(target);
	}
}
2.4.1.5	第五步:创建Dao接口和实现类并使用注解让spring管理
Dao层接口和AccountRowMapper与基于xml配置的时候相同。略

@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {

	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	@Override
	public Account findAccountById(Integer id) {
		List<Account> list = jdbcTemplate.query("select * from account where id = ? ",new AccountRowMapper(),id);
		return list.isEmpty()?null:list.get(0);
	}

	@Override
	public Account findAccountByName(String name) {
		List<Account> list =  jdbcTemplate.query("select * from account where name = ? ",new AccountRowMapper(),name);
		if(list.isEmpty()){
			return null;
		}
		if(list.size()>1){
			throw new RuntimeException("结果集不唯一,不是只有一个账户对象");
		}
		return list.get(0);
	}

	@Override
	public void updateAccount(Account account) {
		jdbcTemplate.update("update account set money = ? where id = ? ",account.getMoney(),account.getId());
	}
}
2.4.2	配置步骤
2.4.2.1	第一步:配置数据源和JdbcTemplate
<!-- 配置数据源 -->
<bean id="dataSource" 
			class="org.springframework.jdbc.datasource.DriverManagerDataSource">
	<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
	<property name="url" value="jdbc:mysql:///spring_day04"></property>
	<property name="username" value="root"></property>
	<property name="password" value="1234"></property>
</bean>


2.4.2.2	第二步:配置事务管理器并注入数据源
<!-- 配置JdbcTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
	<property name="dataSource" ref="dataSource"></property>
</bean>
2.4.2.3	第三步:在业务层使用@Transactional注解
@Service("accountService")
@Transactional(readOnly=true,propagation=Propagation.SUPPORTS)
public class AccountServiceImpl implements IAccountService {
	
	@Autowired
	private IAccountDao accountDao;

	@Override
	public Account findAccountById(Integer id) {
		return accountDao.findAccountById(id);
	}

	@Override
	@Transactional(readOnly=false,propagation=Propagation.REQUIRED)
	public void transfer(String sourceName, String targeName, Float money) {
		//1.根据名称查询两个账户
		Account source = accountDao.findAccountByName(sourceName);
		Account target = accountDao.findAccountByName(targeName);
		//2.修改两个账户的金额
		source.setMoney(source.getMoney()-money);//转出账户减钱
		target.setMoney(target.getMoney()+money);//转入账户加钱
		//3.更新两个账户
		accountDao.updateAccount(source);
		//int i=1/0;
		accountDao.updateAccount(target);
	}
}

该注解的属性和xml中的属性含义一致。该注解可以出现在接口上,类上和方法上。
出现接口上,表示该接口的所有实现类都有事务支持。
出现在类上,表示类中所有方法有事务支持
出现在方法上,表示方法有事务支持。
以上三个位置的优先级:方法>>接口
2.4.2.4	第四步:在配置文件中开启spring对注解事务的支持
<!-- 开启spring对注解事务的支持 -->
<tx:annotation-driven transaction-manager="transactionManager"/> 

2.5 基于纯注解的声明式事务控制(配置方式)重点

2.5.1 环境搭建

在这里插入图片描述

2.5.1.2	第二步:创建一个类用于加载spring的配置并指定要扫描的包
/**
 * 用于初始化spring容器的配置类
 */
@Configuration
@ComponentScan(basePackages="com.itheima")
public class SpringConfiguration {

}
2.5.1.3	第三步:创建数据库表和实体类
和基于xml的配置相同。略
2.5.1.4	第四步:创建业务层接口和实现类并使用注解让spring管理
业务层接口和基于xml配置的时候相同。略

/**
 * 账户的业务层实现类
 */
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
	@Autowired
	private IAccountDao accountDao;

	@Override
	public Account findAccountById(Integer id) {
		return accountDao.findAccountById(id);
	}

	@Override
	public void transfer(String sourceName, String targeName, Float money) {
		//1.根据名称查询两个账户
		Account source = accountDao.findAccountByName(sourceName);
		Account target = accountDao.findAccountByName(targeName);
		//2.修改两个账户的金额
		source.setMoney(source.getMoney()-money);//转出账户减钱
		target.setMoney(target.getMoney()+money);//转入账户加钱
		//3.更新两个账户
		accountDao.updateAccount(source);
		int i=1/0;
		accountDao.updateAccount(target);
	}
}

2.5.1.5	第五步:创建Dao接口和实现类并使用注解让spring管理
Dao层接口和AccountRowMapper与基于xml配置的时候相同。略

@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {

	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	@Override
	public Account findAccountById(Integer id) {
		List<Account> list = jdbcTemplate.query("select * from account where id = ? ",new AccountRowMapper(),id);
		return list.isEmpty()?null:list.get(0);
	}

	@Override
	public Account findAccountByName(String name) {
		List<Account> list =  jdbcTemplate.query("select * from account where name = ? ",new AccountRowMapper(),name);
		if(list.isEmpty()){
			return null;
		}
		if(list.size()>1){
			throw new RuntimeException("结果集不唯一,不是只有一个账户对象");
		}
		return list.get(0);
	}

	@Override
	public void updateAccount(Account account) {
		jdbcTemplate.update("update account set money = ? where id = ? ",account.getMoney(),account.getId());
	}
}

2.5.2	配置步骤
2.5.2.1	第一步:使用@Bean注解配置数据源
@Bean(name = "dataSource")
	public DataSource createDS() throws Exception {
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setUsername("root");
		dataSource.setPassword("123");
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");
		dataSource.setUrl("jdbc:mysql:///spring3_day04");
		return dataSource;
	}
2.5.2.2	第二步:使用@Bean注解配置配置事务管理器
@Bean
public PlatformTransactionManager 
		createTransactionManager(@Qualifier("dataSource") DataSource dataSource) {
	return new DataSourceTransactionManager(dataSource);
}
2.5.2.3	第三步:使用@Bean注解配置JdbcTemplate
@Bean
public JdbcTemplate createTemplate(@Qualifier("dataSource") DataSource dataSource) 
{
	return new JdbcTemplate(dataSource);
}
2.5.2.4	第四步:在需要控制事务的业务层实现类上使用@Transactional注解
@Service("accountService")
@Transactional(readOnly=true,propagation=Propagation.SUPPORTS)
public class AccountServiceImpl implements IAccountService {
	
	@Autowired
	private IAccountDao accountDao;

	@Override
	public Account findAccountById(Integer id) {
		return accountDao.findAccountById(id);
	}

	@Override
	@Transactional(readOnly=false,propagation=Propagation.REQUIRED)
	public void transfer(String sourceName, String targeName, Float money) {
		//1.根据名称查询两个账户
		Account source = accountDao.findAccountByName(sourceName);
		Account target = accountDao.findAccountByName(targeName);
		//2.修改两个账户的金额
		source.setMoney(source.getMoney()-money);//转出账户减钱
		target.setMoney(target.getMoney()+money);//转入账户加钱
		//3.更新两个账户
		accountDao.updateAccount(source);
		//int i=1/0;
		accountDao.updateAccount(target);
	}
}

该注解的属性和xml中的属性含义一致。该注解可以出现在接口上,类上和方法上。
出现接口上,表示该接口的所有实现类都有事务支持。
出现在类上,表示类中所有方法有事务支持
出现在方法上,表示方法有事务支持。
以上三个位置的优先级:方法>>接口。
2.5.2.5	第五步:使用@EnableTransactionManagement开启spring对注解事务的的支持
@Configuration
@EnableTransactionManagement
public class SpringTxConfiguration {
	//里面配置数据源,配置JdbcTemplate,配置事务管理器。在之前的步骤已经写过了。
}


spring+mybatis整合:


1、环境搭建
	1) 导jar 10+3+1+1
	2) 配置文件spring.xml
		<!-- 1 配置数据源
			<bean id="ds" class="BasicDataSource"
				<property name="driverClassName"
				<property name="url"
				<property name="username"
				<property name="password" value=""
		<!-- 2 配置SqlSessionFactory
			<bean id="f" class="SqlSessionFactoryBean">
				<prperty name="dataSoure" ref="ds"
				<prperty name="mapperLocations" value="classpath:com/baizhi/yyl/mapper/*Mapper.xml"
		<!-- 3 配置dao
			<bean class="MapperScannerConfigurer">
				<property name="basePackage" value="com.baizhi.yyl.dao"
				<property name="sqlSessionFactoryBeanName" value="f"
		<!-- 4 配置service
		<!-- 5 配置事务管理器,并指定事务属性
			<bean id="tm" class="DataSourceTransactionManager">
				<property name="dataSource" ref="ds"
			<tx:advice id="txAdvice" transaction-manager="tm">
				<tx:attributes>
					<tx:method name="query*" propagation="SUPPORTS" read-only="true"/>
					<tx:method name="*"/>
					
		<aop:config>
		<!-- 6 配置切入点
			<aop:pointcut id="" expression="execution(* com.baizhi.yyl.service..*SerivceImpl.*(..))"/>
		<!-- 7 配置组装切面
		
		
理论:
	通知4种
	数据的脏读
	传播属性中的required和supports的区别 及使用场 景

整合struts2

  1. Spring整合struts2后管理strus2的 action实现类的创建

  2. 在这里插入图片描述
    . 在WEB环境下,初始化Spring工厂的时机是在应用启动的时候。Spring采用监听器的机制实现在启动WEB应用时初始化Spring工厂: ContextLoaderListener (初始化工厂的监听器)

    1. 整合流程
      3.1 搭建开发环境
      - 引入依赖 pom.xml
      - 引入配置文件
      -jdbc.properties
      -log4j.properties
      -mapper.xml
      -struts.xml
      -spring-core.xml
      - 初始化配置

整合SSM

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

IOC:
	<bean id="" class="" scope="">
	@Component("beanId")  组件,可以用在service /dao/action/servlet
		@Service   用在业务类
		@Controller  用在action类
		@repository   用在dao类
	@Scope("prototype")
	public class Action1{
		@Resource(name="service的beanId")
		private UserService sercvice;
		public void setService(UserService sercvice;){
		
		}
	}
	
基于注释式开发的整合:
1. 导jar(25个)
2. 配置文件(3个)
	struts.xml
	spring.xml(7项)
		1)注解的包扫描   <context:component-scan base-package="com.baizhi.yyl.service,com.baizhi.yyl.action"/>
		2)引入db的小配置文件
		3)数据源
		4)sqlsessionfactory
		5)dao
		6)事务管理器
		7)事务注解生效   <tx:annotation-driven transaction-manager="tm"/>
	web.xml(3项)
		struts2的前端控制器
		srping的web工厂
		spring.xml的位置

开发步骤:
1. sql
2. conf
3. test
4. entity
5. dao   先接口,后mapper
	使用main/junit 非web环境的工厂进行测试
6. service  先接口,后实现类
		@Service("userService")
		@Transactional
		public class UserServiceImpl impelments....{
			//DI
			@Resource(name="userDao")
			private UserDao dao;
			
			// 注册
			public void reg(User user){
				dao.insert(user);
			}
			// 查询
			@Transactional(propagation=Propagation.SUPPORTS,readOnly=true)
			public List<user> queryAll(){
			}
		}
	使用main/junit 非web环境的工厂进行测试
7. 输入界面
8. aciton包   DmiAction   在struts.xml配置 <action  name="" class="dmiAction(Line60)">
	@Controller("dmiAction")
	@Scope("prototype")
	public class DmiAction {
		// DI
		@Resource(name="userService")  (Line41)
		prvate UserService service;
		
		// 1 收参
		
		
		public String reg(){
			// 2 业务类
			// 3 跳转
		}
	}
9. 输出界面
10. 路径整合
11. 测试
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

从入门小白到小黑

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值