ssmp易忘点

Posted 夜雨夕眠

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ssmp易忘点相关的知识,希望对你有一定的参考价值。

一. spring

1.1 IOC

pom依赖


<?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.hzq</groupId>
    <artifactId>father_model</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>spring_IOC</module>
        <module>spring_AOP</module>
    </modules>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <spring-version>5.2.6.RELEASE</spring-version>

    </properties>
    <dependencies>
<!--        junit测试-->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>5.6.2</version>
            <scope>test</scope>
        </dependency>
<!--        spring核心-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring-version}</version>
        </dependency>
<!--        spring测试模块-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring-version}</version>
        </dependency>
    </dependencies>

</project>

1.1.1 装载bean

1.使用xml配置bean

将bean类装载到IOC容器中使用bean标签

<?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">
<!--    1.通过xml装载bean,并使用set方法进行依赖注入-->
    <bean id="user" class="com.hzq.beans.User"></bean>
</beans>

注入简单类型属性(set方法注入)

<bean id="user" class="com.hzq.beans.User">
    <property name="id" value="1"/>
    <property name="name" value="hzq"/>
    <property name="age" value="25"/>
    <property name="sex" value="男"/>
</bean>

注入简单类型属性(构造方法注入)

<bean id="user" class="com.hzq.beans.User">
        <constructor-arg name="id" value="2"/>
				<constructor-arg name="name" value="wsb"/>
        <constructor-arg name="sex" value="男"/>
        <constructor-arg name="age" value="25"/>
</bean>

注入null值

<bean id="user" class="com.hzq.beans.User">
    <property name="id" value="1"/>
  	<property name="name">
  		<null></null>
  	</property>
    <property name="age" value="25"/>
    <property name="sex" value="男"/>
</bean>

注入集合类型的属性

<bean id="collectionBean" class="com.hzq.beans.CollectionBean">
        <property name="array">
            <array>
                <value>a</value>
                <value>b</value>
                <value>c</value>
            </array>
        </property>
        <property name="list">
            <list>
                <value>l</value>
                <value>i</value>
                <value>s</value>
                <value>t</value>
            </list>
        </property>
        <property name="set">
            <set>
                <value>s</value>
                <value>e</value>
                <value>t</value>
            </set>
        </property>
        <property name="map">
            <map>
                <entry key="1" value="m"></entry>
                <entry key="2" value="a"></entry>
                <entry key="3" value="p"></entry>
            </map>
        </property>
    </bean>

注入bean类型的属性

<!--    注入bean类型的数据-->
    <bean id="student" class="com.hzq.beans.Student">
        <property name="id" value="1"/>
        <property name="name" value="hzq"/>
        <property name="age" value="25"/>
        <property name="sex" value="男"/>
<!--        school属性是一个bean,注入使用ref-->
        <property name="school" ref="school"/>
    </bean>
    <bean id="school" class="com.hzq.beans.School">
        <property name="name" value="天平"/>
        <property name="students">
            <list>
<!--                当集合的泛型为一个bean时,可以使用在list内部去配置-->
<!--                如果已经在其他地方配置好了,可以使用<ref>标签引进来-->
                <bean class="com.hzq.beans.Student">
                    <property name="name" value="wsb"/>
                    <property name="id" value="2"/>
                    <property name="age" value="25"/>
                    <property name="sex" value="男"/>
                    <property name="school" ref="school"/>
                </bean>
                <ref bean="student"/>
            </list>
        </property>
    </bean>

配置工程bean

1.创建需要工程生产的bean类

/**
 * @Classname Usb
 * @Date 2021/5/18 上午10:48
 * @author hzq
 */
package com.hzq.beans;

public class Usb {

}

2.工厂bean的创建,需要实现FactoryBean<>接口

/**
 * @Classname USBFactory
 * @Date 2021/5/18 上午10:48
 * @author hzq
 */
package com.hzq.beans;

import org.springframework.beans.factory.FactoryBean;

public class UsbFactory implements FactoryBean<Usb> {

    //这个方法是生产bean的方法
    @Override
    public Usb getObject() throws Exception {
        return new Usb();
    }
    //这个方法是返回被生产的bean的类型
    @Override
    public Class<?> getObjectType() {
        return Usb.class;
    }

    //生产的bean是否是单例
    @Override
    public boolean isSingleton() {
        return false;
    }
}

3.装载到xml配置中

<!--    虽然装载到IOC容器的是UsbFactory,但从IOC容器中获取时得到的是Usb示例-->
    <bean id="usb" class="com.hzq.beans.UsbFactory"></bean>

4.测试

/**
     * 通过bean工厂来创建bean
     */
    @Test
    public void test5(){
        Usb usb1 = context.getBean("usb", Usb.class);
        Usb usb2 = context.getBean("usb", Usb.class);
        System.out.println(usb1 == usb2);
    }
//返回结果为false,因为我们在工厂中的isSingleton()方法中返回的是false,所以Usb实例是多例的.

设置普通bean是单例还是多例

<!-- scope属性为singleton时为单例,这是默认的选项 -->
<bean id="school" class="com.hzq.beans.School" scope="singleton" />
<!-- scope属性为prototype时为多例 -->
<bean id="school" class="com.hzq.beans.School" scope="prototype" />

2. 使用注解配置bean

  1. 在xml配置中开启组件扫描
<!--    开启组件扫描,并配置扫描的包-->
    <context:component-scan base-package="com.hzq.beans"/>
  1. 在bean类上加上@Component注解(也可以是@Controller,@Service,@Repository,它们4个注解的作用都是一样的)
/**
 * @Classname Father
 * @Date 2021/5/18 上午11:31
 * @author hzq
 */
package com.hzq.beans;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

@Component
public class Father {
    private String name;
    private Son son;

    @Override
    public String toString() {
        return "Father{" +
                "name=\'" + name + \'\\\'\' +
                ", son=" + son +
                \'}\';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Son getSon() {
        return son;
    }

    public void setSon(Son son) {
        this.son = son;
    }
}

  1. 在bean的属性或者set方法上加上注解实现依赖注入
/**
 * @Classname Father
 * @Date 2021/5/18 上午11:31
 * @author hzq
 */
package com.hzq.beans;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


@Component
public class Father {
    //基本数据类型或者String使用@Value注解注入
    @Value("hzq")
    private String name;
    //复杂类型使用@Autowired或者@Qualifier注解注入
    @Autowired
    @Qualifier("son")
    private Son son;

    @Override
    public String toString() {
        return "Father{" +
                "name=\'" + name + \'\\\'\' +
                ", son=" + son +
                \'}\';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Son getSon() {
        return son;
    }

    public void setSon(Son son) {
        this.son = son;
    }
}

1.1.2 bean的生命周期

1、生命周期

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

2、默认的生命周期
(1)通过构造器创建 bean 实例(无参数构造)
(2)为 bean 的属性设置值和对其他 bean 引用(调用 set 方法)
(3)调用 bean 的初始化的方法(需要进行配置初始化的方法)
(4)bean 可以使用了(对象获取到了)
(5)当容器关闭时候,调用 bean 的销毁的方法(需要进行配置销毁的方法)

3、加上后置处理器后的生命周期

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

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

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

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

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

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

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

4、后置处理器的用法

  1. 创建后置处理器,需要实现接口BeanPostProcessor
/**
 * @Classname MyPostProcessor
 * @Date 2021/5/18 上午11:18
 * @author hzq
 */
package com.hzq.processor;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class MyPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("初始化方法之前"+bean);
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("初始化方法之后"+bean);
        return bean;
    }
}

  1. 将后置处理器配置到IOC容器中即可
<bean id="myPostProcessor" class="com.hzq.processor.MyPostProcessor"/>
  1. 之后所有的bean在执行init方法的前会使用后置处理器中的postProcessBeforeInitialization方法,执行完init方法后会执行后置处理器的postProcessAfterInitialization方法

1.2 AOP

使用AOP还需要引入aspects模块

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
    <version>${spring-version}</version>
</dependency>

通知共有五种类型

(1) 前置通知

(2) 后置通知

(3) 环绕通知 (重点)

(4)最终通知

(5)异常通知

ps:环绕通知可以终止方法的执行.

在使用AOP之前需要先创建一个通知类

/**
 * @Classname MyAdvice
 * @Date 2021/5/18 下午4:45
 * @author hzq
 */
package com.hzq.advice;

import org.aspectj.lang.ProceedingJoinPoint;

/**
 * 自定义的通知类
 */
public class MyAdvice {
    //前置通知
    public void before(){
        System.out.println("before........");
    }
    //最终通知
    public void after(){
        System.out.println("after........");
    }
    //返回通知
    public void afterReturn(){
        System.out.println("afterReturn........");
    }
    //环绕通知
    public void around(ProceedingJoinPoint point) throws Throwable {
        System.out.println("around1........");
        point.proceed();
        System.out.println("around1........");
    }
    //异常通知
    public void afterThrowing(){
        System.out.println("afterThrowing........");
    }
}

1.2.1使用xml配置AOP

<!--    添加通知类-->
    <bean id="myAdvice" class="com.hzq.advice.MyAdvice"/>
<!--    添加被增强类-->
    <bean id="myService" class="com.hzq.service.MyService"/>
<!--    AOP的配置标签-->
    <aop:config>
<!--        配置切入点-->
        <aop:pointcut id="point" expression="execution(* com.hzq.service.*.*(..))"/>
<!--        切入通知-->
        <aop:aspect id="advice" ref="myAdvice">
<!--            切入最终通知-->
            <aop:after method="after" pointcut-ref="point"/>
<!--            切入返回通知-->
            <aop:after-returning method="afterReturn" pointcut-ref="point"/>
<!--            切入异常通知-->
            <aop:after-throwing method="afterThrowing" pointcut-ref="point"/>
<!--            切入环绕通知-->
            <aop:around method="around" pointcut-ref="point"/>
<!--            切入前置通知-->
            <aop:before method="before" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>

1.2.2 使用注解配置AOP

在上面创建好的通知类上添加注解如下:

/**
 * @Classname MyAdvice
 * @Date 2021/5/18 下午4:45
 * @author hzq
 */
package com.hzq.advice;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 自定义的通知类
 */
@Component
@Aspect
@Order(1)
public class MyAdviceAnnotation {

    @Pointcut("execution(* com.hzq.service.*.*(..))")
    public void pointcut(){ }

    //前置通知
    @Before("pointcut()")
    public void before(){
        System.out.println("before........");
    }
    //最终通知
    @After("pointcut()")
    public void after(){
        System.out.println("after........");
    }
    //返回通知
    @AfterReturning("pointcut()")
    public void afterReturn(){
        System.out.println("afterReturn........");
    }
    //环绕通知
    @Around("pointcut()")
    public void around(ProceedingJoinPoint point) throws Throwable {
        System.out.println("around1........");
        point.proceed();
        System.out.println("around2........");
    }
    //异常通知
    @AfterThrowing("pointcut()")
    public void afterThrowing(){
        System.out.println("afterThrowing........");
    }
}

ps:@Order注解是用来配置多个通知类切入同一个切入点的执行顺序,数字越小,优先级越高

然后在xml中开启AOP的注解

<!--    开启组件扫描-->
    <context:component-scan base-package="com.hzq"/>
<!--    开启AOP注解代理-->
    <aop:aspectj-autoproxy/>

1.3 JDBC

需要增加依赖如下

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>${spring-version}</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.23</version>
</dependency>
<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.47</version>
</dependency>

事前准备:

  1. 创建数据库表,创建实例类等
  2. 配置JDBC
dev.url=jdbc:mysql:///learn_mysql
dev.driver=com.mysql.jdbc.Driver
dev.username=root
dev.password=960828
  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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--    开启组件扫描-->
    <context:component-scan base-package="com.hzq"/>
<!--    引入JDBC配置文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>
<!--    配置数据库连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="username" value="${dev.username}"/>
        <property name="password" value="${dev.password}"/>
        <property name="url" value="${dev.url}"/>
        <property name="driverClassName" value="${dev.driver}"/>
    </bean>
<!--    配置JdbcTemplate-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

1.3.1 jdbc执行数据库操作

  1. 查询一条记录
public Student getStudentById(Integer id) {
        String sql = "select * from students where id = ?";
        Student student = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<Student>(Student.class), id);
        return student;
}
  1. 查询多条记录
public List<Student> getAllStudent(){
        String sql = "select * from students";
        List<Student> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Student.class));
        return list;
}
  1. 查询单个数据,如查询数据库中数据的数量
public Integer getCount() {
        String sql = "select count(*) from students";
        Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
        return count;
}
  1. 修改数据(只演示插入操作,更新与删除操作类似)
public Integer insert(Student student) {
        String sql = "insert into students(name,age,sex) values(?,?,?)";
        int i = jdbcTemplate.update(sql, student.getName(), student.getAge(), student.getSex());
        return i;
}
  1. 批量操作(只演示更新操作,插入与删除操作类似)
public void batchUpdate(List<Object[]> list){
        String sql = "update students set age = ? where id = ?";
        jdbcTemplate.batchUpdate(sql,list);
}

1.3.2 事务

添加依赖

<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-aspects</artifactId>
   <version>${spring-version}</version>
</dependency>
  1. 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:tx="http://www.springframework.org/schema/tx"
       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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--    开启组件扫描-->
    <context:component-scan base-package="com.hzq"/>
<!--    引入JDBC配置文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>
<!--    配置数据库连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="username" value="${dev.username}"/>
        <property name="password" value="${dev.password}"/>
        <property name="url" value="${dev.url}"/>
        <property name="driverClassName" value="${dev.driver}"/>
    </bean>
<!--    配置JdbcTemplate-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>
<!--    配置事务管理器-->
    <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
<!--    配置事务的通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="transMoney" read-only="false" isolation="REPEATABLE_READ" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
<!--    配置切入点与切面-->
    <aop:config>
        <aop:pointcut id="pc" expression="execution(* com.hzq.service.UserService.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pc"/>
    </aop:config>
</beans>
  1. 注解配置事务

在Service类上加上事务的注解

/**
 * @Classname UserService
 * @Date 2021/5/18 下午7:18
 * @author hzq
 */
package com.hzq.service;

import com.hzq.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(readOnly = true,propagation = Propagation.REQUIRED)
public class UserService {
    @Autowired
    private UserDao userDao;
    @Transactional(readOnly = false)
    public void transMoney(Integer from, Integer to, Integer money) {
        userDao.subMoney(from,money);
//        int i = 10/0;
        userDao.addMoney(to,money);
    }
}

在xml中开启事务的注解驱动

<!--    开启事务的注解驱动-->
    <tx:annotation-driven/>

二. Mybatis

[官方文档](mybatis – MyBatis 3 | 入门)

mybatis的核心技术就是mybatis主配置文件,mapper映射文件的配置,动态sql的书写以及与spring的整合

其他非重要技术有一二级缓存技术,逆向工程等

2.1 基本使用

  1. 引入依赖
<dependencies>
<!--        mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
<!--        mybatis依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.6</version>
        </dependency>
<!--        junit测试依赖-->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>5.6.2</version>
            <scope>test</scope>
        </dependency>
</dependencies>
  1. 创建mybatis主配置文件与jdbc配置文件

jdbc.properties

dev.username=root
dev.password=960828
dev.url=jdbc:mysql:///learn_mysql
dev.driver=com.mysql.jdbc.Driver

mybatis.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--    引入jdbc配置文件-->
    <properties resource="jdbc.properties"></properties>
<!--    打开mybatis日志功能,将日志输出到控制台-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
<!--    选择数据库配置-->
    <environments default="development">
<!--        定义数据库配置-->
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${dev.driver}"/>
                <property name="url" value="${dev.url}"/>
                <property name="username" value="${dev.username}"/>
                <property name="password" value="${dev.password}"/>
            </dataSource>
        </environment>
    </environments>
<!--    加载mapper映射文件-->
    <mappers>
        <mapper resource="mapper/StudentDao.xml"/>
    </mappers>
</configuration>
  1. 创建实体类与dao层接口

Student.java

/**
 * @Classname User
 * @Date 2021/5/18 上午9:45
 * @author hzq
 */
package com.hzq.domain;

public class Student {
    private Integer id;
    private String name;
    private String sex;
    private Integer age;

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name=\'" + name + \'\\\'\' +
                ", sex=\'" + sex + \'\\\'\' +
                ", age=" + age +
                \'}\';
    }

    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 String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Student() {
    }
}

StudentDao.java

/**
 * @Classname StudentDao
 * @Date 2021/5/19 下午4:32
 * @author hzq
 */
package com.hzq.dao;

import com.hzq.domain.Student;

public interface StudentDao {
    Student getStudentById(Integer id);
}

ps:接口不需要创建实现类

  1. 创建dao层接口的映射文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace命名空间需要填写dao层接口的全类名,表示这个mapper映射文件与这个接口相对应-->
<mapper namespace="com.hzq.dao.StudentDao">
<!--    id代表这个sql语句映射的是接口中的哪个方法,resultType代表这个方法的返回值类型-->
    <select id="getStudentById" resultType="com.hzq.domain.Student">
        select * from students where id = #{id}
    </select>
</mapper>
  1. 测试
@Test
    public void test1() throws IOException {
        //读取mybatis主配置文件
        InputStream resource = Resources.getResourceAsStream("mybatis.xml");
        //创建SqlSessionFactoryBuilder对象,此对象只是用来创建SqlSessionFactory对象的,
        //使用完就可以立即丢弃了
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        //SqlSessionFactoryBuilder对象通过mybatis主配置文件来创建SqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = builder.build(resource);
        //SQLSessionFactory对象打开一个Session对象,这个Session对象就是用来执行sql语句的
        SqlSession session = sqlSessionFactory.openSession();
        //通过Session对象获取Dao层接口的动态代理对象
        StudentDao studentDao = session.getMapper(StudentDao.class);
        //dao层接口的实现类去执行mapper映射文件中配置的sql语句
        Student student = studentDao.getStudentById(9);
        System.out.println(student);
    }

总结

mybatis已经将jdbc的功能进行了封装,我们在使用时需要注意的只有以下几点:

(1) 书写mybatis的主配置文件

(2) 编写dao层的接口

(3) 编写与dao层接口相对应的映射文件

(4) 通过SqlSession调用getMapper()方法来获取dao层接口的实现类

(5)调用dao层接口实现类的方法

2.2 mybatis主配置文件

[主配置文件的官方文档](mybatis – MyBatis 3 | 配置)

2.3 mapper映射文件配置

[mapper映射文件官方文档](mybatis – MyBatis 3 | XML 映射器)

2.4 动态sql

[动态sql官方文档](mybatis – MyBatis 3 | 动态 SQL)

2.5 与spring的整合

添加依赖

<dependency>
   <groupId>org.mybatis</groupId>
   <artifactId>mybatis-spring</artifactId>
   <version>2.0.5</version>
</dependency>
  1. 创建实体类与dao层接口

  2. 创建创建mapper映射文件

  3. 创建mybatis主配置文件

  4. 创建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: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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--    开启组件扫描-->
    <context:component-scan base-package="com.hzq"/>
<!--    引入jdbc配置-->
    <context:property-placeholder location="classpath:jdbc.properties"/>
<!--    数据库连接池配置-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="username" value="${dev.username}"/>
        <property name="password" value="${dev.password}"/>
        <property name="url" value="${dev.url}"/>
        <property name="driverClassName" value="${dev.driver}"/>
    </bean>
<!--    开启mapper接口的扫描-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" id="mapperScannerConfigurer">
        <property name="basePackage" value="com.hzq.dao"/>
    </bean>
<!--    配置SqlSessionFactory-->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory">
        <property name="dataSource" ref="dataSource"/>
<!--        指定mapper映射文件位置-->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
<!--        指定mybatis主配置文件文职-->
        <property name="configLocation" value="classpath:mybatis.xml"/>
    </bean>
<!--    配置事务管理器-->
    <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
<!--    开启注解事务-->
    <tx:annotation-driven/>

</beans>
  1. 测试
/**
 * @Classname Test1
 * @Date 2021/5/20 上午10:05
 * @author hzq
 */
package test;

import com.hzq.controller.StudentController;
import com.hzq.domain.Student;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;

@ExtendWith(SpringExtension.class)
@ContextConfiguration("classpath:spring.xml")
public class Test1 {
    @Autowired
    private StudentController controller;
    //测试添加数据
    @Test
    public void test1(){
        Student student = new Student();
        student.setAge(20);
        student.setName("小强");
        student.setSex("男");
        Integer integer = controller.addStudent(student);
        System.out.println(integer);
    }
//    测试修改数据
    @Test
    public void test2(){
        Student student = new Student();
        student.setId(9);
        student.setAge(20);
        student.setName("小李");
        student.setSex("男");
        Integer integer = controller.updateStudentById(student);
        System.out.println(integer);
    }
//    测试查询数据
    @Test
    public void test3(){
        Student student = controller.getStudentById(9);
        System.out.println(student);
    }
}

三. springMVC

引入依赖

<!--    springmvc的依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.6.RELEASE</version>
    </dependency>
<!--    aop的依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>5.2.6.RELEASE</version>
    </dependency>

3.1 常规配置

web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
<!--    指定spring的配置文件位置-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:application.xml</param-value>
    </context-param>
<!--    使用context的创建监听器初始化spring容器-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
<!--    配置中央控制器-->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--        指定mvc配置文件,当中央控制器加载后就自动加载mvc配置-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
<!--        让中央控制器在容器启动时加载-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
<!--    配置编码过滤器-->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceRequestEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>forceResponseEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

springMVC配置文件

<?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:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--    开启组件扫描-->
    <context:component-scan base-package="com.hzq" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
<!--    开启注解驱动-->
    <mvc:annotation-driven/>
<!--    指定静态资源存放位置,当前端控制器的uri为/*时必须指定-->
    <mvc:resources mapping="/static/*" location="classpath:static/"/>

</beans>

3.2 自定义转换器

  1. 创建自定义的转换器,该转换器需要实现Converter<>接口
/**
 * @Classname StringToDateConverter
 * @Date 2021/5/20 下午7:16
 * @author hzq
 */
package com.hzq.converter;

import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class StringToDateConverter implements Converter<String, Date> {
    @Override
    public Date convert(String s) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = dateFormat.parse(s);
        } catch (ParseException e) {
            throw new RuntimeException("日期转换异常!");
        }
        return date;

    }
}

  1. 将配置转换器
<!--    配置转换器-->
    <bean class="org.springframework.context.support.ConversionServiceFactoryBean" id="conversionService">
        <property name="converters">
            <list>
                <bean class="com.hzq.converter.StringToDateConverter"/>
            </list>
        </property>
    </bean>
<!--    开启注解驱动并选择自己配置的转换服务-->
    <mvc:annotation-driven conversion-service="conversionService"/>

3.3 拦截器

  1. 最低定义拦截器需要实现HandleInteceptor接口
/**
 * @Classname MyInteceptor
 * @Date 2021/5/22 下午4:52
 * @author hzq
 */
package com.hzq.interceptor;

import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyInteceptor implements HandlerInterceptor {
    /**
     * 在处理器方法调用之前拦截
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String status = request.getParameter("status");
        System.out.println(status);
        if (!StringUtils.isEmpty(status)){
            return Boolean.valueOf(status);
        }
        return false;
    }

    /**
     * 在处理器方法调用完成之后执行
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle.....");
    }

    /**
     * 当视图解析器解析完成后执行
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion.....");
      	//会将下面的内容输出
        response.getOutputStream().write("你好世界!".getBytes());
      	//也可以在这里处理controller执行期间的异常
	      //response.getOutputStream().write(ex.getMessage().getBytes());
    }
}

四. ssm整合

  1. 导入依赖
<dependencies>
<!--    spring核心依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.2.6.RELEASE</version>
    </dependency>
<!--    springAOP依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>5.2.6.RELEASE</version>
    </dependency>
<!--    spring jdbc tx 等依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.2.6.RELEASE</version>
    </dependency>
<!--    spring MVC依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.6.RELEASE</version>
    </dependency>
<!--    mybatis与spring整合依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>2.0.5</version>
    </dependency>
<!--    mybatis依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.6</version>
    </dependency>
<!--    德鲁伊连接池依赖-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.23</version>
    </dependency>
<!--    mysql驱动-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.47</version>
    </dependency>
<!--    jackson依赖-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.9.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.9.0</version>
    </dependency>
  </dependencies>
  1. springMVC配置文件
<?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:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--    springMVC容器只扫描controller-->
    <context:component-scan base-package="com.hzq.controller" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
<!--    开启注解驱动-->
    <mvc:annotation-driven/>
<!--    配置静态资源映射-->
    <mvc:resources mapping="/static/**" location="classpath:static/**"/>
<!--    配置视图解析器-->
    <mvc:view-resolvers>
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/jsp/"/>
            <property name="suffix" value=".jsp"/>
        </bean>
    </mvc:view-resolvers>
</beans>
  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: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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--    开启组件扫描,排除controller的扫描-->
    <context:component-scan base-package="com.hzq" use-default-filters="true">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
<!--    引入jdbc配置-->
    <context:property-placeholder location="classpath:jdbc.properties"/>
<!--    数据库连接池配置-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="username" value="${dev.username}"/>
        <property name="password" value="${dev.password}"/>
        <property name="url" value="${dev.url}"/>
        <property name="driverClassName" value="${dev.driver}"/>
    </bean>
<!--    开启mapper接口的扫描-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" id="mapperScannerConfigurer">
        <property name="basePackage" value="com.hzq.dao"/>
    </bean>
<!--    配置SqlSessionFactory-->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory">
        <property name="dataSource" ref="dataSource"/>
<!--        指定mapper映射文件位置-->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
<!--        指定mybatis主配置文件位置-->
        <property name="configLocation" value="classpath:mybatis.xml"/>
    </bean>
<!--    配置事务管理器-->
    <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
<!--    开启注解事务-->
    <tx:annotation-driven/>

</beans>
  1. web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
<!--    配置前端控制器-->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--        指定springMVC配置文件-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springMVC.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
<!--    配置编码过滤器-->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceRequestEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>forceResponseEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
<!--    指定spring配置文件-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:application.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>

五.mybatis-plus

使用查看文档

官方文档

在上面ssm整合的基础之上做修改

  1. 导入依赖
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus</artifactId>
    <version>3.4.3</version>
</dependency>

ps:引入 MyBatis-Plus 之后请不要再次引入 MyBatis 以及 MyBatis-Spring,以避免因版本差异导致的问题。

  1. 在spring的配置文件中进行修改

ssm

<!--    配置SqlSessionFactory-->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory">
        <property name="dataSource" ref="dataSource"/>
<!--        指定mapper映射文件位置-->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
<!--        指定mybatis主配置文件位置-->
        <property name="configLocation" value="classpath:mybatis.xml"/>
    </bean>

ssmp

!--    配置SqlSessionFactory-->
    <bean class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean" id="sqlSessionFactory">
        <property name="dataSource" ref="dataSource"/>
<!--        指定mapper映射文件位置-->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
<!--        指定mybatis主配置文件位置-->
        <property name="configLocation" value="classpath:mybatis.xml"/>
    </bean>

这样就将mybatis-plus整合到ssm中了.

以上是关于ssmp易忘点的主要内容,如果未能解决你的问题,请参考以下文章

日常易忘点记录

关于Verilog HDL的一些技巧易错易忘点(不定期更新)

易错易忘点

系统运维易忘点总结之七

python学习手册中的一些易忘的点(4-7部分)

JavaSe