Spring5学习笔记

课程内容介绍

目录

1.Spring概述

1.1 Spring框架概述

1.2 Spring特点

1.3 Spring入门案例

1.3.1 引入Spring的ioc基本包

1.3.2 新建项目,新建lib文件夹,将jar包导入

1.3.3 将jar包导入项目

1.3.4 创建普通类,在这个类创建普通方法

1.3.5 创建 Spring 配置文件,在配置文件配置创建的对象

1.3.6 进行测试代码编写

2. IOC容器

2.1 什么是IOC

2.2 IOC底层原理

2.3 IOC(BeanFactory 接口)

2.4 IOC 操作 Bean 管理(概念)

2.5 IOC 操作 Bean 管理(基于 xml 方式)

2.5.1 基于 xml 方式创建对象

2.5.2 基于 xml 方式注入属性

2.5.3.第一种注入方式:使用 set 方法进行注入

2.5.4 第二种注入方式:使用有参数构造进行注入

2.5.5 p 名称空间注入(了解)

2.6 IOC 操作 Bean 管理(xml 注入其他类型属性)

2.7 IOC 操作 Bean 管理(xml 注入集合属性)

2.8 IOC 操作 Bean 管理(FactoryBean) 

2.9 IOC 操作 Bean 管理(bean 作用域)

2.10 IOC 操作 Bean 管理(bean 生命周期)

2.11 IOC 操作 Bean 管理(xml 自动装配)

2.11 IOC 操作 Bean 管理(外部属性文件)

2.12 IOC 操作 Bean 管理(基于注解方式)

3. AOP

3.1 什么是 AOP

3.2 AOP(JDK 动态代理)

3.3 AOP(术语)

3.3.1 连接点

3.3.2 切入点

3.3.3 通知(增强)

3.3.4 切面

3.4 AOP(准备工作)

3.5 AOP 操作(AspectJ 注解)

3.6 AOP 操作(AspectJ 配置文件)

4. JdbcTemplate(概念和准备)

4.1 JdbcTemplate 操作数据库(添加)

4.2 JdbcTemplate 操作数据库(修改和删除)

4.3 JdbcTemplate 操作数据库(查询返回某个值)

4.4 JdbcTemplate 操作数据库(查询返回对象)

4.5 JdbcTemplate 操作数据库(查询返回集合)

4.6 JdbcTemplate 操作数据库(批量操作)

5. 事务操作

5.1 事务概念

5.2 事务的四个特性(ACID)

5.2.1原子性( Atomicity )

5.2.2 一致性( Consistency )

5.2.3 隔离性( Isolation )

5.2.4 持久性( Durability )

5.3 事务操作(搭建事务操作环境)

5.3.1 银行转账案例

5.4 事务操作(Spring 事务管理介绍)

5.5 事务操作(注解声明式事务管理)

5.6 事务操作(声明式事务管理参数配置)

5.6.1 propagation:事务传播行为

​5.6.2 ioslation:事务隔离级别

5.6.3 Serializable

5.6.4 事务的其他属性

5.7 事务操作(XML 声明式事务管理)

5.8 事务操作(完全注解声明式事务管理)



1.Spring概述

1. 1 Spring框架概述

  1. Spring是轻量级的开源JavaEE框架
  2. Spring可以解决企业应用开发的复杂性
  3. Spring有两个核心部分:
    • IOC:控制反转,把创建对象的过程交给Spring进行管理
    • Aop:面向切面,不修改进行功能增强

1.2 Spring特点

  1. 方面解耦,简化开发
  2. Aop 编程支持
  3. 方便程序的测试
  4. 方便进行事务操作
  5. 方便集成各种其他优秀的框架
  6. 降低Java EE API的使用难度

1.3Spring入门案例

1.3.1 引入Spring的ioc基本包

1.3.2 新建项目,新建lib文件夹,将jar包导入

1.3.3 将jar包导入项目

导入基本jar包后单击ok,完成

1.3.4 创建普通类,在这个类创建普通方法

User类中有一个Add()方法:

package com.Spring;

public class User {
    public void add(){
        System.out.println("add方法被执行...");
    }
}

1.3.5 创建 Spring 配置文件,在配置文件配置创建的对象

bean1.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">
        <!--配置User对象创建-->
    <bean id="user" class="com.Spring.User"></bean>//id是User类的别名

</beans>

使用<bean> 标签,完成对User对象的创建,bean标签有两个属性:

id:用于给类起别名

class:该类的路径

1.3.6 进行测试代码编写

package com.Spring.testdemo;

import com.Spring.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class TestSpring5 {
    @Test
    public void testAdd(){
        //加载Spring配置文件
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean1.xml");//配置文件名
        //获取配置对象
        User user = context.getBean("user", User.class);//类别名,类名
        System.out.println(user);
        user.add();
    }
}

结果输出:

user类地址,Add()方法输出111

2. IOC容器

2.1 什么是IOC

  1. 控制反转,把对象的创建和对象之间的调用过程,交给Spring进行管理。
  2. 使用IOC的目的:为了使耦合度降低。
  3. 入门案例就是IOC实现。

2.2 IOC底层原理

xml解析、工厂模式、反射

 画图理解:

2.3 IOC(BeanFactory 接口)

1、IOC 思想基于 IOC 容器完成,IOC 容器底层就是对象工厂
2、Spring 提供 IOC 容器实现两种方式:(两个接口)
(1)BeanFactory:IOC 容器基本实现,是 Spring 内部的使用接口,不提供开发人员进行使用
* 加载配置文件时候不会创建对象,在获取对象(使用)才去创建对象
(2)ApplicationContext:BeanFactory 接口的子接口,提供更多更强大的功能,一般由开发人员进行使用
* 加载配置文件时候就会把在配置文件对象进行创建
3、ApplicationContext 接口有实现类

2.4 IOC 操作 Bean 管理(概念)

1、什么是 Bean 管理

Bean 管理指的是两个操作 :

(1)Spring 创建对象

(2)Spirng 注入属性

2、Bean 管理操作有两种方式

(1)基于 xml 配置文件方式实现

(2)基于注解方式实现

2.5 IOC 操作 Bean 管理(基于 xml 方式)

2.5.1 基于 xml 方式创建对象

<!--配置User对象创建-->
<bean id="user" class="com.spring5.User"></bean>

(1)在 spring 配置文件中,使用 bean 标签,标签里面添加对应属性,就可以实现对象创建 (2)在 bean 标签有很多属性,介绍常用的属性 * id 属性:唯一标识 * class 属性:类全路径(包类路径)

(3)创建对象时候,默认也是执行无参数构造方法完成对象创建

2.5.2 基于 xml 方式注入属性

(1)DI:依赖注入,就是注入属性

2.5.3.第一种注入方式:使用 set 方法进行注入

(1)创建类,定义属性和对应的 set 方法

/**
     * 演示使用 set 方法进行注入属性
     */
    public class Book {
        //创建属性
        private String bname;
        private String bauthor;
        //创建属性对应的 set 方法
        public void setBname(String bname) {
            this.bname = bname;
        }
        public void setBauthor(String bauthor) {
            this.bauthor = bauthor;
        }
    }

(2)在 spring 配置文件配置对象创建,配置属性注入

    <bean id="book" class="com.atguigu.spring5.Book">
     <!--使用 property 完成属性注入
        name:类里面属性名称
        value:向属性注入的值
     -->
         <property name="bname" value="西游记"></property>
         <property name="bauthor" value="吴承恩"></property>
    </bean>

2.5.4 第二种注入方式:使用有参数构造进行注入

(1)创建类,定义属性,创建属性对应有参数构造方法

 /**
     * 使用有参数构造注入
     */
    public class Orders {
        //属性
        private String oname;
        private String address;
        //有参数构造
        public Orders(String oname,String address) {
            this.oname = oname;
            this.address = address;
        }
    }

(2)在 spring 配置文件中进行配置

<!--3 有参数构造注入属性-->
    <bean id="orders" class="com.atguigu.spring5.Orders">
        <constructor-arg name="oname" value="电脑"></constructor-arg>
        <constructor-arg name="address" value="China"></constructor-arg>
    </bean>

2.5.5 p 名称空间注入(了解)

(1)使用 p 名称空间注入,可以简化基于 xml 配置方式

第一步 添加 p 名称空间在配置文件中

<?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:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans.xsd">

第二步 进行属性注入,在 bean 标签里面进行操作 

<bean id="book" class="com.spring5.Book" p:bname="西游记" 
p:bauthor="吴承恩"></bean>

2.6 IOC 操作 Bean 管理(xml 注入其他类型属性)

1、字面量

(1)null 值

<!--null 值-->
<property name="address">
 <null/>
</property>

(2)属性值包含特殊符号

<!--属性值包含特殊符号
 1 把<>进行转义 &lt; &gt;
 2 把带特殊符号内容写到 CDATA
-->
<property name="address">
 <value><![CDATA[<<南京>>]]></value>
</property>

 2、注入属性-外部 bean

(1)创建两个类 service 类和 dao 类

(2)在 service 调用 dao 里面的方法

(3)在 spring 配置文件中进行配置

public class UserService {
    //创建UserDao类型属性,生成set方法
    private UserDao userDao;
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
    public void add() {
        System.out.println("service add...............");
        userDao.update();
    }  
}
<!--1 service 和 dao 对象创建-->
    <bean id="userService" class="com.spring5.service.UserService">
    <!--注入 userDao 对象
    name 属性:类里面属性名称
    ref 属性:创建 userDao 对象 bean 标签 id 值
    -->
    <property name="userDao" ref="userDaoImpl"></property>
    </bean>
    <bean id="userDaoImpl" class="com.spring5.dao.UserDaoImpl"></bean>

3、注入属性-内部 bean

(1)一对多关系:部门和员工 一个部门有多个员工,一个员工属于一个部门 部门是一,员工是多 (2)在实体类之间表示一对多关系,员工表示所属部门,使用对象类型属性进行表示

//部门类
public class Dept {
    private String dname;
    public void setDname(String dname) {
        this.dname = dname;
    }
}
//员工类
public class Emp {
    private String ename;
    private String gender;
    //员工属于某一个部门,使用对象形式表示
    private Dept dept;
    public void setDept(Dept dept) {
        this.dept = dept;
    }
    public void setEname(String ename) {
        this.ename = ename;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
}

(3)在 spring 配置文件中进行配置

<!--内部 bean-->
    <bean id="emp" class="com.spring5.bean.Emp">
        <!--设置两个普通属性-->
        <property name="ename" value="lucy"></property>
        <property name="gender" value="女"></property>
        <!--设置对象类型属性-->
        <property name="dept">
            <bean id="dept" class="com.spring5.bean.Dept">
                <property name="dname" value="安保部"></property>
            </bean>
        </property>
    </bean>

2.7 IOC 操作 Bean 管理(xml 注入集合属性)

1、注入数组类型属性

2、注入 List 集合类型属性

3、注入 Map 集合类型属性

(1)创建类,定义数组、list、map、set 类型属性,生成对应 set 方法

public class Stu {
    //1 数组类型属性
    private String[] courses;
    //2 list 集合类型属性
    private List<String> list;
    //3 map 集合类型属性
    private Map<String,String> maps;
    //4 set 集合类型属性
    private Set<String> sets;
    public void setSets(Set<String> sets) {
        this.sets = sets;
    }
    public void setCourses(String[] courses) {
        this.courses = courses;
    }
    public void setList(List<String> list) {
        this.list = list;
    }
    public void setMaps(Map<String, String> maps) {
        this.maps = maps;
    }
}

 (2)在 spring 配置文件进行配置

<!--1 集合类型属性注入-->
    <bean id="stu" class="com.spring5.collectiontype.Stu">
        <!--数组类型属性注入-->
        <property name="courses">
            <array>
                <value>java 课程</value>
                <value>数据库课程</value>
            </array>
        </property>
        <!--list 类型属性注入-->
        <property name="list">
            <list>
                <value>张三</value>
                <value>小三</value>
            </list>
        </property>
        <!--map 类型属性注入-->
        <property name="maps">
            <map>
                <entry key="JAVA" value="java"></entry>
                <entry key="PHP" value="php"></entry>
            </map>
        </property>
        <!--set 类型属性注入-->
        <property name="sets">
            <set>
                <value>MySQL</value>
                <value>Redis</value>
            </set>
        </property>
    </bean>

4、在集合里面设置对象类型值

<!--创建多个 course 对象-->
    <bean id="course1" class="com.spring5.collectiontype.Course">
        <property name="cname" value="Spring5 框架"></property>
    </bean>
    <bean id="course2" class="com.spring5.collectiontype.Course">
        <property name="cname" value="MyBatis 框架"></property>
    </bean>
    <!--注入 list 集合类型,值是对象-->
    <property name="courseList">
        <list>
            <ref bean="course1"></ref>
            <ref bean="course2"></ref>
        </list>
    </property>

5、把集合注入部分提取出来

(1)在 spring 配置文件中引入名称空间 util 

<?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:p="http://www.springframework.org/schema/p"
           xmlns:util="http://www.springframework.org/schema/util"
           xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans.xsd
 http://www.springframework.org/schema/util 
http://www.springframework.org/schema/util/spring-util.xsd">

 (2)使用 util 标签完成 list 集合注入提取

<!--1 提取 list 集合类型属性注入-->
<util:list id="bookList">
 <value>西游记</value>
 <value>红楼梦/value>
 <value>金瓶梅</value>
</util:list>
<!--2 提取 list 集合类型属性注入使用-->
<bean id="book" class="com.spring5.collectiontype.Book">
     <property name="list" ref="bookList"></property>
</bean>

2.8 IOC 操作 Bean 管理(FactoryBean) 

1、Spring 有两种类型 bean,一种普通 bean,另外一种工厂 bean(FactoryBean)

2、普通 bean:在配置文件中定义 bean 类型就是返回类型

3、工厂 bean:在配置文件定义 bean 类型可以和返回类型不一样

        第一步 创建类,让这个类作为工厂 bean,实现接口 FactoryBean

        第二步 实现接口里面的方法,在实现的方法中定义返回的 bean 类型 

public class MyBean implements FactoryBean<Course> {
    //定义返回 bean
    @Override
    public Course getObject() throws Exception {
        Course course = new Course();
        course.setCname("abc");
        return course;
    }
    @Override
    public Class<?> getObjectType() {
        return null;
    }
    @Override
    public boolean isSingleton() {
        return false;
    }
}
<bean id="myBean" class="com.atguigu.spring5.factorybean.MyBean">
</bean>
@Test
public void test3() {
        ApplicationContext context =
        new ClassPathXmlApplicationContext("bean3.xml");
        Course course = context.getBean("myBean", Course.class);
        System.out.println(course);
        }

2.9 IOC 操作 Bean 管理(bean 作用域)

1、在 Spring 里面,设置创建 bean 实例是单实例还是多实例

2、在 Spring 里面,默认情况下,bean 是单实例对象

3、如何设置单实例还是多实例

(1)在 spring 配置文件 bean 标签里面有属性(scope)用于设置单实例还是多实例

(2)scope 属性值

        第一个值 默认值,singleton,表示是单实例对象

        第二个值 prototype,表示是多实例对象

(3)singleton 和 prototype 区别 第一 singleton 单实例,prototype 多实例 第二 设置 scope 值是 singleton 时候,加载 spring 配置文件时候就会创建单实例对象 设置 scope 值是 prototype 时候,不是在加载 spring 配置文件时候创建 对象,在调用 getBean 方法时候创建多实例对象

2.10 IOC 操作 Bean 管理(bean 生命周期)

1、生命周期

(1)从对象创建到对象销毁的过程

2、bean 生命周期

(1)通过构造器创建 bean 实例(无参数构造)

(2)为 bean 的属性设置值和对其他 bean 引用(调用 set 方法)

(3)调用 bean 的初始化的方法(需要进行配置初始化的方法)

(4)bean 可以使用了(对象获取到了)

(5)当容器关闭时候,调用 bean 的销毁的方法(需要进行配置销毁的方法)

3、演示 bean 生命周期

public class Orders {
    //无参数构造
    public Orders() {
        System.out.println("第一步 执行无参数构造创建 bean 实例");
    }
    private String oname;
    public void setOname(String oname) {
        this.oname = oname;
        System.out.println("第二步 调用 set 方法设置属性值");
    }
    //创建执行的初始化的方法
    public void initMethod() {
        System.out.println("第三步 执行初始化的方法");
    }
    //创建执行的销毁的方法
    public void destroyMethod() {
        System.out.println("第五步 执行销毁的方法");
    }
}

 xml配置

<bean id="orders" class="com.spring5.bean.Orders" initmethod="initMethod" destroy-method="destroyMethod">
<property name="oname" value="手机"></property>
</bean>

测试类

@Test
public void testBean3() {
// ApplicationContext context =
// new ClassPathXmlApplicationContext("bean4.xml");
        ClassPathXmlApplicationContext context =
        new ClassPathXmlApplicationContext("bean4.xml");
        Orders orders = context.getBean("orders", Orders.class);
        System.out.println("第四步 获取创建 bean 实例对象");
        System.out.println(orders);
        //手动让 bean 实例销毁
        context.close();
        }

 

4、bean 的后置处理器,bean 生命周期有七步

(1)通过构造器创建 bean 实例(无参数构造)

(2)为 bean 的属性设置值和对其他 bean 引用(调用 set 方法)

(3)把 bean 实例传递 bean 后置处理器的方法 postProcessBeforeInitialization

(4)调用 bean 的初始化的方法(需要进行配置初始化的方法)

(5)把 bean 实例传递 bean 后置处理器的方法 postProcessAfterInitialization

(6)bean 可以使用了(对象获取到了)

(7)当容器关闭时候,调用 bean 的销毁的方法(需要进行配置销毁的方法) 

5、演示添加后置处理器效果

(1)创建类,实现接口 BeanPostProcessor,创建后置处理器

public class MyBeanPost implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName)
            throws BeansException {
        System.out.println("在初始化之前执行的方法");
        return bean;
    }
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName)
            throws BeansException {
        System.out.println("在初始化之后执行的方法");
        return bean;
    }
}
<!--配置后置处理器-->
<bean id="myBeanPost" class="com.spring5.bean.MyBeanPost"></bean>

 2.11 IOC 操作 Bean 管理(xml 自动装配)

1、什么是自动装配
(1)根据指定装配规则(属性名称或者属性类型),Spring 自动将匹配的属性值进行注入

2、演示自动装配过程

实现自动装配
bean 标签属性 autowire,配置自动装配
autowire 属性常用两个值:
byName 根据属性名称注入 ,注入值 bean 的 id 值和类属性名称一样
byType 根据属性类型注入
(1)根据属性名称自动注入

<bean id="emp" class="com.spring5.autowire.Emp" autowire="byName">
<!--<property name="dept" ref="dept"></property>-->
</bean>
<bean id="dept" class="com.spring5.autowire.Dept"></bean>

(2)根据属性类型自动注入 

<bean id="emp" class="com.spring5.autowire.Emp" autowire="byType">
<!--<property name="dept" ref="dept"></property>-->
</bean>
<bean id="dept" class="com.spring5.autowire.Dept"></bean>

 2.11 IOC 操作 Bean 管理(外部属性文件)

1、直接配置数据库信息
(1)配置德鲁伊连接池
(2)引入德鲁伊连接池依赖 jar 包

<!--直接配置连接池-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
    <property name="url" value="jdbc:mysql://localhost:3306/userDb"></property>
    <property name="username" value="root"></property>
    <property name="password" value="root"></property>
</bean>

2、引入外部属性文件配置数据库连接池
(1)创建外部属性文件,properties 格式文件,写数据库信息 

(2)把外部 properties 属性文件引入到 spring 配置文件中
* 引入 context 名称空间
xmlns:context="http://www.springframework.org/schema/context"

http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
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/util
http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">

在 spring 配置文件使用标签引入外部属性文件

<!--引入外部属性文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--配置连接池-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    <property name="driverClassName" value="${prop.driverClass}"></property>
    <property name="url" value="${prop.url}"></property>
    <property name="username" value="${prop.userName}"></property>
    <property name="password" value="${prop.password}"></property>
</bean>

2.12 IOC 操作 Bean 管理(基于注解方式)

1、什么是注解
(1)注解是代码特殊标记,格式:@注解名称(属性名称=属性值, 属性名称=属性值..)
(2)使用注解,注解作用在类上面,方法上面,属性上面
(3)使用注解目的:简化 xml 配置
2、Spring 针对 Bean 管理中创建对象提供注解
(1)@Component
(2)@Service
(3)@Controller
(4)@Repository
* 上面四个注解功能是一样的,都可以用来创建 bean 实例
3、基于注解方式实现对象创建
第一步 引入依赖

        spring-aop-5.2.6.RELEASE.jar

第二步 开启组件扫描

扫描com.spring包

<!--开启组件扫描
1 如果扫描多个包,多个包使用逗号隔开
2 扫描包上层目录
-->
<context:component-scan base-package="com.spring"></context:component-scan>

第三步 创建类,在类上面添加创建对象注解

//在注解里面 value 属性值可以省略不写,
//默认值是类名称,首字母小写
//UserService -- userService
@Component(value = "userService")
//<bean id="userService" class=".."/>
public class UserService {
public void add() {
System.
out.println("service add.......");
    }
}

4、开启组件扫描细节配置

<!--示例 1
use-default-filters="false" 表示现在不使用默认 filter,自己配置 filter
context:include-filter ,设置扫描哪些内容
-->
<context:component-scan base-package="com.spring5" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

<!--示例 2
下面配置扫描包所有内容
context:exclude-filter: 设置哪些内容不进行扫描
-->
<context:component-scan base-package="com.spring">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

5、基于注解方式实现属性注入
(1)@Autowired:根据属性类型进行自动装配
第一步 把 service 和 dao 对象创建,在 service 和 dao 类添加创建对象注解
第二步 在 service 注入 dao 对象,在 service 类添加 dao 类型属性,在属性上面使用注解

@Service
public class UserService {
//定义 dao 类型属性
//不需要添加 set 方法
//添加注入属性注解
@Autowired
private UserDao userDao;
    public void add() {
        System.out.println("service add.......");
        userDao.add();
    }
}

(2)@Qualifier:根据名称进行注入
这个@Qualifier 注解的使用,和上面@Autowired 一起使用

//定义 dao 类型属性
//不需要添加 set 方法
//添加注入属性注解
@Autowired
//根据类型进行注入
@Qualifier(value = "userDaoImpl1")
//根据名称进行注入
private UserDao userDao;

(3)@Resource:可以根据类型注入,可以根据名称注入

//@Resource //根据类型进行注入
@Resource(name = "userDaoImpl1")
//根据名称进行注入
private UserDao userDao;

(4)@Value:注入普通类型属性

//@Value:注入普通类型属性
@Value(value = "abc")
private String name;

6、完全注解开发
(1)创建配置类,替代 xml 配置文件

@Configuration
//作为配置类,替代 xml 配置文件
@ComponentScan(basePackages = {"com.spring"})
public class SpringConfig {
}

(2)编写测试类

@Test
public void testService2() {
//加载配置类
    ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
    UserService userService = context.getBean("userService",UserService.class);
    System.out.println(userService);
    userService.add();
}

3. AOP

3.1 什么是 AOP

  1. 面向切面编程(方面),利用 AOP 可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
  2. 通俗描述:不通过修改源代码方式,在主干功能里面添加新功能

使用登录例子说明 AOP

3.2 AOP(JDK 动态代理)

 1、使用 JDK 动态代理,使用 Proxy 类里面的方法创建代理对象

(1)调用 newProxyInstance 方法


        方法有三个参数:
                第一参数,类加载器
                第二参数,增强方法所在的类,这个类实现的接口,支持多个接口
                第三参数,实现这个接口 InvocationHandler,创建代理对象,写增强的部分


2、编写 JDK 动态代理代码
(1)创建接口,定义方法

public interface UserDao {
    public int add(int a,int b);
    public String update(String id);
}

(2)创建接口实现类,实现方法

public class UserDaoImpl implements UserDao {
    @Override
    public int add(int a, int b) {
        return a+b;
    }
    @Override
    public String update(String id) {
        return id;
    }
}

(3)使用 Proxy 类创建接口代理对象

public class JDKProxy {
    public static void main(String[] args) {
//创建接口实现类代理对象
        Class[] interfaces = {UserDao.class};
        UserDaoImpl userDao = new UserDaoImpl();
        UserDao dao = (UserDao)Proxy.newProxyInstance(JDKProxy.class.getClassLoader(),
                interfaces, new UserDaoProxy(userDao));
        int result = dao.add(1, 2);
        System.out.println("result:"+result);
    }
}
//创建代理对象代码
class UserDaoProxy implements InvocationHandler {
    //1 把创建的是谁的代理对象,把谁传递过来
    //有参数构造传递
    private Object obj;
    public UserDaoProxy(Object obj) {
        this.obj = obj;
    }
    //增强的逻辑
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws
            Throwable {
        //方法之前
        System.out.println("方法之前执行...."+method.getName()+" :传递的参数..."+ Arrays.
        toString(args));
        //被增强的方法执行
        Object res = method.invoke(obj, args);
        //方法之后
        System.out.println("方法之后执行...."+obj);
        return res;
    }
}

3.3 AOP(术语)

3.3.1 连接点

概念:类里面哪些方法可以增强,这些方法称为连接点。

3.3.2 切入点

概念:实际被真正增强的方法,称为切入点。

3.3.3 通知(增强)

1. 概念:实际增强的逻辑部分称为通知(增强)

2.通知的多种类型:

  1. 前置通知
  2. 后置通知
  3. 环绕通知
  4. 异常通知
  5. 最终通知

3.3.4 切面

概念:把通知应用到切入点的过程,是动作。

3.4 AOP(准备工作)

1、Spring 框架一般都是基于 AspectJ 实现 AOP 操作
(1)AspectJ 不是 Spring 组成部分,独立 AOP 框架,一般把 AspectJ 和 Spirng 框架一起使
用,进行 AOP 操作
2、基于 AspectJ 实现 AOP 操作
(1)基于 xml 配置文件实现
(2)基于注解方式实现(推荐
3、在项目工程里面引入 AOP 相关依赖
4、切入点表达式
(1)切入点表达式作用:知道对哪个类里面的哪个方法进行增强
(2)语法结构: execution([权限修饰符] [返回类型] [类全路径] [方法名称]([参数列表]) )

举例 1:对 com.dao.BookDao 类里面的 add() 进行增强
execution(* com.dao.BookDao.add(..))

举例 2:对 com.dao.BookDao 类里面的所有的方法进行增强
execution(* com.dao.BookDao.* (..))

举例 3:对 com.dao 包里面所有类,类里面所有方法进行增强
execution(* com.dao.*.* (..))

3.5 AOP 操作(AspectJ 注解)

1、创建类,在类里面定义方法

public class User {
    public void add() {
        System.out.println("add.......");
    }
}

2、创建增强类(编写增强逻辑)
(1)在增强类里面,创建方法,让不同方法代表不同通知类型

//增强的类
public class UserProxy {
    public void before() {
        //前置通知
        System.out.println("before......");
    }
}

3、进行通知的配置
(1)在 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: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">

<!-- 开启注解扫描 -->
<context:component-scan base-package="com.spring5.aopanno">
</context:component-scan>

(2)使用注解创建 User 和 UserProxy 对象

//被增强的类
@Component
public class User{
//被增强的类
@Component
public class UserProxy{

(3)在增强类上面添加注解 @Aspect

//增强的类
@Component
@Aspect//生成代理对象
public class UserProxy {

(4)在 spring  xml配置文件中开启生成代理对象

<!-- 开启 Aspect 生成代理对象-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

4、配置不同类型的通知
(1)在增强类的里面,在作为通知方法上面添加通知类型注解,使用切入点表达式配置

//增强的类
@Component
@Aspect
//生成代理对象
public class UserProxy {
    //前置通知
    //@Before 注解表示作为前置通知
    @Before(value = "execution(* com.spring5.aopanno.User.add(..))")
    public void before() {
        System.out.println("before.........");
    }
    
    //后置通知(返回通知)
    @AfterReturning(value = "execution(* com.spring5.aopanno.User.add(..))")
    public void afterReturning() {
        System.out.println("afterReturning.........");
    }
    
    //最终通知
    @After(value = "execution(* com.spring5.aopanno.User.add(..))")
    public void after() {
        System.out.println("after.........");
    }
    
    //异常通知
    @AfterThrowing(value = "execution(* com.spring5.aopanno.User.add(..))")
    public void afterThrowing() {
        System.out.println("afterThrowing.........");
    }
    
    //环绕通知
    @Around(value = "execution(* com.spring5.aopanno.User.add(..))")
    public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("环绕之前.........");
        //被增强的方法执行
        proceedingJoinPoint.proceed();
        System.out.println("环绕之后.........");
    }
}

6、有多个增强类多同一个方法进行增强,设置增强类优先级
(1)在增强类上面添加注解 @Order(数字类型值),数字类型值越小优先级越高

@Component
@Aspect
@Order(1)
public class PersonProxy

7、完全使用注解开发
(1)创建配置类,不需要创建 xml 配置文件

@Configuration
@ComponentScan(basePackages = {"com.spring"})
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class ConfigAop {

}

3.6 AOP 操作(AspectJ 配置文件)

1、创建两个类,增强类和被增强类,创建方法

增强类 book
2、在 spring 配置文件中创建两个类对象

<!--创建对象-->
<bean id="book" class="com.atguigu.spring5.aopxml.Book"></bean>
<bean id="bookProxy" class="com.atguigu.spring5.aopxml.BookProxy"></bean>

3、在 spring 配置文件中配置切入点

<!--配置 aop 增强-->
<aop:config>
<!--切入点-->
<aop:pointcut id="p" expression="execution(*
com.atguigu.spring5.aopxml.Book.buy(..))"/>
<!--配置切面-->
<aop:aspect ref="bookProxy">
<!--增强作用在具体的方法上-->
<aop:before method="before" pointcut-ref="p"/>
</aop:aspect>
</aop:config>

4. JdbcTemplate(概念和准备)

1、什么是 JdbcTemplate
(1)Spring 框架对 JDBC 进行封装,使用 JdbcTemplate 方便实现对数据库操作

2、准备工作
(1)引入相关 jar 包

(2)在 spring 配置文件配置数据库连接池

<!-- 数据库连接池 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
    <property name="url" value="jdbc:mysql:///user_db" />
    <property name="username" value="root" />
    <property name="password" value="123456" />
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
</bean>

(3)配置 JdbcTemplate 对象,注入 DataSource

<!-- JdbcTemplate 对象 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <!--注入 dataSource-->
    <property name="dataSource" ref="dataSource"></property>
</bean>

(4)创建 service 类,创建 dao 类,在 dao 注入 jdbcTemplate 对象

* 组件扫描

<!-- 组件扫描 -->
<context:component-scan base-package="com.spring"></context:component-scan>

* 配置文件

Service

@Service
public class BookService {
    //注入 dao
    @Autowired
    private BookDao bookDao;
}

Dao

@Repository
public class BookDaoImpl implements BookDao {
    //注入 JdbcTemplate
    @Autowired
    private JdbcTemplate jdbcTemplate;
}

4.1 JdbcTemplate 操作数据库(添加)

1、对应数据库创建实体类

package com.spring5;

public class User {
    private String userId;
    private String username;

    public void setUserId(String userId) {
        this.userId = userId;
    }
    public void setUsername(String username) {
        this.username = username;
    }
}

2、编写 service 和 dao
(1)在 dao 进行数据库添加操作
(2)调用 JdbcTemplate 对象里面 update 方法实现添加操作

update(String sql,Object ... args)

方法有两个参数
第一个参数:sql 语句
第二个参数:可变参数,设置 sql 语句值

@Repository
public class BookDaoImpl implements BookDao {
    //注入 JdbcTemplate
    @Autowired
    private JdbcTemplate jdbcTemplate;
    //添加的方法
    @Override
    public void add(Book book) {
        //1 创建 sql 语句
        String sql = "insert into t_book values(?,?,?)";
        //2 调用方法实现
        Object[] args = {book.getUserId(), book.getUsername()};
        int update = jdbcTemplate.update(sql,args);
        System.out.println(update);
    }
}

3、测试类

   @Test
    public void testJdbcTemplate() {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        BookService bookService = context.getBean("bookService",BookService.class);
        Book book = new Book();
        book.setUserId("1");
        book.setUsername("java");
        bookService.addBook(book);
    }

4.2 JdbcTemplate 操作数据库(修改和删除)

1、修改

@Override
public void updateBook(Book book) {
    String sql = "update t_book set username=?,ustatus=? where user_id=?";
    Object[] args = {book.getUsername(),book.getUserId()};
    int update = jdbcTemplate.update(sql, args);
    System.out.println(update);
}

2、删除

    @Override
    public void delete(String id) {
        String sql = "delete from t_book where user_id=?";
        int update = jdbcTemplate.update(sql, id);
        System.out.println(update);
    }

4.3 JdbcTemplate 操作数据库(查询返回某个值)

1、查询表里面有多少条记录,返回是某个值
2、使用 JdbcTemplate 实现查询返回某个值代码

queryForObject(String sql,Class<T> requiredType)

有两个参数
         第一个参数:sql 语句
         第二个参数:返回类型 Class

//查询表记录数
@Override
public int selectCount() {
    String sql = "select count(*) from t_book";
    Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
    return count;
}

4.4 JdbcTemplate 操作数据库(查询返回对象)

1、场景:查询图书详情
2、JdbcTemplate 实现查询返回对象

queryForObject(String sql, RowMapper<T> rowMapper, Object... args);

 有三个参数

  1. 第一个参数:sql 语句
  2. 第二个参数:RowMapper 是接口,针对返回不同类型数据,使用这个接口里面实现类完成数据封装
  3.  第三个参数:sql 语句值
//查询返回对象
    @Override
    public Book findBookInfo(String id) {
        String sql = "select * from t_book where user_id=?";
        //调用方法
        Book book = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<Book>(Book.class), id);
        return book;
    }    

4.5 JdbcTemplate 操作数据库(查询返回集合)

1、场景:查询图书列表分页...
2、调用 JdbcTemplate 方法实现查询返回集合

query(String sql, RowMapper<T> rowMapper, Object... args);
有三个参数
        第一个参数:sql 语句
        第二个参数:RowMapper 是接口,针对返回不同类型数据,使用这个接口里面实现类完成数据封装
       第三个参数:sql 语句值

//查询返回集合
    @Override
    public List<Book> findAllBook() {
        String sql = "select * from t_book";
        //调用方法
        List<Book> bookList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Book>(Book.class));
        return bookList;
    }

4.6 JdbcTemplate 操作数据库(批量操作)

1、批量操作:操作表里面多条记录
2、JdbcTemplate 实现批量添加操作

batchUpdate(String sql, RowMapper<T> rowMapper, Object... args);

有两个参数:
        第一个参数:sql 语句
        第二个参数:List 集合,添加多条记录数据

//批量添加
@Override
public void batchAddBook(List<Object[]> batchArgs) {
    String sql = "insert into t_book values(?,?,?)";
    int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
    System.out.println(Arrays.toString(ints));
}
//批量添加测试
List<Object[]> batchArgs = new ArrayList<>();
Object[] o1 = {"3","java","a"};
Object[] o2 = {"4","c++","b"};
Object[] o3 = {"5","MySQL","c"};
batchArgs.add(o1);
batchArgs.add(o2);
batchArgs.add(o3);
//调用批量添加
bookService.batchAdd(batchArgs);

3、JdbcTemplate 实现批量修改操作

//批量修改
@Override
public void batchUpdateBook(List<Object[]> batchArgs) {
    String sql = "update t_book set username=?,ustatus=? where user_id=?";
    int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
    System.out.println(Arrays.toString(ints));
}
//批量修改
List<Object[]> batchArgs = new ArrayList<>();
Object[] o1 = {"java0909","a3","3"};
Object[] o2 = {"c++1010","b4","4"};
Object[] o3 = {"MySQL1111","c5","5"};
batchArgs.add(o1);
batchArgs.add(o2);
batchArgs.add(o3);
//调用方法实现批量修改
bookService.batchUpdate(batchArgs);

4、JdbcTemplate 实现批量删除操作

//批量删除
@Override
public void batchDeleteBook(List<Object[]> batchArgs) {
    String sql = "delete from t_book where user_id=?";
    int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
    System.out.println(Arrays.toString(ints));
}
//批量删除
List<Object[]> batchArgs = new ArrayList<>();Object[] o1 = {"3"};
Object[] o2 = {"4"};
batchArgs.add(o1);
batchArgs.add(o2);
//调用方法实现批量删除
bookService.batchDelete(batchArgs);

5. 事务操作

5.1 事务概念

1、什么是事务
(1)事务是数据库操作最基本单元,逻辑上一组操作,要么都成功,如果有一个失败所有操
作都失败
(2)典型场景:银行转账
                * lucy 转账 100 元 给 mary
                * lucy 少 100,mary 多 100

5.2 事务的四个特性(ACID)

5.2.1原子性( Atomicity )

        原子性是指事务是一个不可分割的工作单位,事务中的操作要么都发生,要么都不发生。

5.2.2 一致性( Consistency )

        数据库总是从一个一致性的状态转移到另一个一致性的状态。一致性确保了即使在执行第三、第四条语句之间时系统崩溃,前面执行的第一、第二条语句也不会生效,因为事务最终没有提交,所有事务中所作的修改也不会保存到数据库中。

5.2.3 隔离性( Isolation )

        一个事务的执行不能其它事务干扰。即一个事务内部的操作及使用的数据对其它并发事务是隔离的,并发执行的各个事务之间不能互相干扰。

5.2.4 持久性( Durability )

    指一个事务一旦提交,它对数据库中的数据的改变就应该是永久性的。接下来的其它操作或故障不应该对其执行结果有任何影响。

        事务中的所有操作要么全部执行,要么都不执行; 如果事务没有原子性的保证,那么在发生系统 故障的情况下,数据库就有可能处于不一致状态。 因而,事务的原子性与一致性是密切相关的。

5.3 事务操作(搭建事务操作环境)

5.3.1 银行转账案例

思路设计

1、创建数据库表,添加记录


2、创建 service,搭建 dao,完成对象创建和注入关系
(1)service 注入 dao,在 dao 注入 JdbcTemplate,在 JdbcTemplate 注入 DataSource

@Service
public class UserService {
    //注入 dao
    @Autowired
    private UserDao userDao;
}
@Repository
public class UserDaoImpl implements UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
}

3、在 dao 创建两个方法:多钱和少钱的方法,在 service 创建方法(转账的方法)

@Repository
public class UserDaoImpl implements UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    //lucy 转账 100 给 mary
    //少钱
    @Override
    public void reduceMoney() {
        String sql = "update t_account set money=money-? where username=?";
        jdbcTemplate.update(sql,100,"lucy");
    }
    //多钱
    @Override
    public void addMoney() {
        String sql = "update t_account set money=money+? where username=?";
        jdbcTemplate.update(sql,100,"mary");
    }
}

@Service
public class UserService {
    //注入 dao
    @Autowired
    private UserDao userDao;

    //转账的方法
    public void accountMoney() {
        //lucy 少 100
        userDao.reduceMoney();
        //mary 多 100
        userDao.addMoney();
        }
} 

 4、上面代码,如果正常执行没有问题的,但是如果代码执行过程中出现异常,有问题

public void accountMoney(){
    try{
        //第一步 开启事务
        //第二步 进行业务操作
        //lucy少100
        userDao.reduceMoney();

        //模拟异常
        int i = 10 / 0;
        
        //mary多100
        userDao.addMoney();
        //第三步 没有发生异常,提交事务
    }catch(Exception e){
        //第四步 出现异常,事务回滚    
    }
}

5.4 事务操作(Spring 事务管理介绍)

1、事务添加到 JavaEE 三层结构里面 Service 层(业务逻辑层)
2、在 Spring 进行事务管理操作
(1)有两种方式:编程式事务管理和声明式事务管理(推荐)
3、声明式事务管理
(1)基于注解方式(推荐)
(2)基于 xml 配置文件方式
4、在 Spring 进行声明式事务管理,底层使用 AOP 原理
5、Spring 事务管理 API
(1)提供一个接口,代表事务管理器,这个接口针对不同的框架提供不同的实现类

5.5 事务操作(注解声明式事务管理)

1、在 spring 配置文件配置事务管理器

<!--创建事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <!--注入数据源-->
    <property name="dataSource" ref="dataSource"></property>
</bean>

2、在 spring 配置文件,开启事务注解
(1)在 spring 配置文件引入名称空间 tx

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

(2)开启事务注解

<!--开启事务注解-->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>

3、在 service 类上面(或者 service 类里面方法上面)添加事务注解
(1)@Transactional,这个注解添加到类上面,也可以添加方法上面
(2)如果把这个注解添加类上面,这个类里面所有的方法都添加事务
(3)如果把这个注解添加方法上面,为这个方法添加事务

@Service
@Transactional
public class UserService {
}

5.6 事务操作(声明式事务管理参数配置)

5.6.1 propagation:事务传播行为

在 service 类上面添加注解@Transactional,在这个注解里面可以配置事务相关参数

        多事务方法直接进行调用,这个过程中事务 是如何进行管理的:

5.6.2 ioslation:事务隔离级别

(1)事务有特性成为隔离性,多事务操作之间不会产生影响。不考虑隔离性产生很多问题
有三个读问题:脏读、不可重复读、虚(幻)读

  • 脏读:一个未提交事务读取到另一个未提交事务的数据
  • 不可重复读:一个未提交事务读取到另一提交事务修改数据
  • 虚读:一个未提交事务读取到另一提交事务添加数据

(2)解决:通过设置事务隔离级别,解决读问题

        数据库事务的隔离级别有4种,由低到高分别为Read uncommitted 、Read committed 、Repeatable read 、Serializable 。而且,在事务的并发操作中可能会出现脏读,不可重复读,幻读。

Read uncommitted

读未提交,顾名思义,就是一个事务可以读取另一个未提交事务的数据。

事例:老板要给程序员发工资,程序员的工资是3.6万/月。但是发工资时老板不小心按错了数字,按成3.9万/月,该钱已经打到程序员的户口,但是事务还没有提交,就在这时,程序员去查看自己这个月的工资,发现比往常多了3千元,以为涨工资了非常高兴。但是老板及时发现了不对,马上回滚差点就提交了的事务,将数字改成3.6万再提交。

分析:实际程序员这个月的工资还是3.6万,但是程序员看到的是3.9万。他看到的是老板还没提交事务时的数据。这就是脏读

Read committed

读提交,顾名思义,就是一个事务要等另一个事务提交后才能读取数据。

事例:程序员拿着信用卡去享受生活(卡里当然是只有3.6万),当他买单时(程序员事务开启),收费系统事先检测到他的卡里有3.6万,就在这个时候!!程序员的妻子要把钱全部转出充当家用,并提交。当收费系统准备扣款时,再检测卡里的金额,发现已经没钱了(第二次检测金额当然要等待妻子转出金额事务提交完)。程序员就会很郁闷,明明卡里是有钱的…

分析:这就是读提交,若有事务对数据进行更新(UPDATE)操作时,读操作事务要等待这个更新操作事务提交后才能读取数据,可以解决脏读问题。但在这个事例中,出现了一个事务范围内两个相同的查询却返回了不同数据,这就是不可重复读。

Repeatable read

重复读,就是在开始读取数据(事务开启)时,不再允许修改操作

事例:程序员拿着信用卡去享受生活(卡里当然是只有3.6万),当他买单时(事务开启,不允许其他事务的UPDATE修改操作),收费系统事先检测到他的卡里有3.6万。这个时候他的妻子不能转出金额了。接下来收费系统就可以扣款了。

分析:重复读可以解决不可重复读问题。写到这里,应该明白的一点就是,不可重复读对应的是修改,即UPDATE操作。但是可能还会有幻读问题。因为幻读问题对应的是插入INSERT操作,而不是UPDATE操作

什么时候会出现幻读?

事例:程序员某一天去消费,花了2千元,然后他的妻子去查看他今天的消费记录(全表扫描FTS,妻子事务开启),看到确实是花了2千元,就在这个时候,程序员花了1万买了一部电脑,即新增INSERT了一条消费记录,并提交。当妻子打印程序员的消费记录清单时(妻子事务提交),发现花了1.2万元,似乎出现了幻觉,这就是幻读。

5.6.3 Serializable

那怎么解决幻读问题? Serializable 序列化

Serializable 是最高的事务隔离级别,在该级别下,事务串行化顺序执行,可以避免脏读、不可重复读与幻读。但是这种事务隔离级别效率低下,比较耗数据库性能,一般不使用。

5.6.4 事务的其他属性

timeout:超时时间
(1)事务需要在一定时间内进行提交,如果不提交进行回滚
(2)默认值是 -1 ,设置时间以秒单位进行计算
readOnly:是否只读
(1)读:查询操作,写:添加修改删除操作
(2)readOnly 默认值 false,表示可以查询,可以添加修改删除操作
(3)设置 readOnly 值是 true,设置成 true 之后,只能查询
rollbackFor:回滚
(1)设置出现哪些异常进行事务回滚
noRollbackFor:不回滚
(1)设置出现哪些异常不进行事务回滚

 

5.7 事务操作(XML 声明式事务管理)

1、在 spring 配置文件中进行配置
第一步 配置事务管理器

第二步 配置通知

第三步 配置切入点和切面

<!--1 创建事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <!--注入数据源-->
    <property name="dataSource" ref="dataSource"></property>
</bean>

<!--2 配置通知-->
<tx:advice id="txadvice">
    <!--配置事务参数-->
    <tx:attributes>
        <!--指定哪种规则的方法上面添加事务-->
        <tx:method name="accountMoney" propagation="REQUIRED"/>
        <!--<tx:method name="account*"/>-->
    </tx:attributes>
</tx:advice>

<!--3 配置切入点和切面-->
<aop:config>
    <!--配置切入点-->
    <aop:pointcut id="pt" expression="execution(*com.atguigu.spring5.service.UserService.*(..))"/>
    <!--配置切面-->
    <aop:advisor advice-ref="txadvice" pointcut-ref="pt"/>
</aop:config>

5.8 事务操作(完全注解声明式事务管理)

创建配置类,使用配置类替代 xml 配置文件

@Configuration
//配置类
@ComponentScan(basePackages = "com.atguigu")
//组件扫描
@EnableTransactionManagement
//开启事务
public class TxConfig {
    //创建数据库连接池
    @Bean
    public DruidDataSource getDruidDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql:///user_db");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        return dataSource;
    }
    //创建 JdbcTemplate 对象
    @Bean
    public JdbcTemplate getJdbcTemplate(DataSource dataSource) {
        //到 ioc 容器中根据类型找到 dataSource
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        //注入 dataSource
        jdbcTemplate.setDataSource(dataSource);return jdbcTemplate;
    }
    //创建事务管理器
    @Bean
    public DataSourceTransactionManager
    getDataSourceTransactionManager(DataSource dataSource) {
        DataSourceTransactionManager transactionManager = new
                DataSourceTransactionManager();
        transactionManager.setDataSource(dataSource);
        return transactionManager;
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值