跟着狂神学习Mybatis的笔记

第一个mabatis程序

1.1、搭建环境

1.1.1、搭建数据库
CREATE DATABASE `mybatis`;

USE `mybatis`;

CREATE TABLE `user`(
	`id` INT(20) NOT NULL PRIMARY KEY,
	`name` VARCHAR(30) DEFAULT NULL,
	`pwd` VARCHAR(30) DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;

INSERT INTO `user`(`id`,`name`,`pwd`) VALUES
(1,'张三','123456'),
(2,'李四','123456'),
(3,'王五','123456'),
(4,'赵六','123456'),
(5,'肖七','123456')
1.1.2、新建项目
  1. 新建一个普通的maven项目

  2. 删除src目录

  3. 导入maven依赖

    <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.2</version>
        </dependency>
        <!--junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>
    

1.2、创建一个模板

1.2.1、编写mybatis的核心配置文件
<?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核心配置文件-->
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode&amp;characterEncodeing=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value=""/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="org/mybatis/example/BlogMapper.xml"/>
    </mappers>
</configuration>
1.2.2、编写mybatis工具类
private static SqlSessionFactory sqlSessionFactory;

static{
    try {
        // 使用mybatis获得sqlSessionFactory对象
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public static SqlSession getSqlSession(){
    return sqlSessionFactory.openSession();
}
1.2.3、编写代码

1、实体类

2、Dao接口

List<User> getUserList();

3、接口实现类(Mapper.xml文件)

接口实现类由原来的UserDaoImpl转变为一个Mapper配置文件

<?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接口
id为接口中的方法名
resultType
-->
<mapper namespace="com.bin.dao.UserDao">
    <select id="getUserList" resultType="com.bin.pojo.User">
        select * from mybatis.user;
    </select>
</mapper>
1.2.4、测试

错误:

org.apache.ibatis.binding.BindingException: Type interface com.bin.dao.UserDao is not known to the MapperRegistry.

MapperRegistry是核心配置文件中注册mappers

  • junit测试
@Test
public void test(){
    // 第一步:获得sqlSession对象
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    // 执行SQL
    UserDao mapper = sqlSession.getMapper(UserDao.class);
    List<User> userList = mapper.getUserList();
    for (User user : userList) {
        System.out.println(user);
    }
    // 关闭
    sqlSession.close();
}

可能遇到的错误:

  1. 配置文件没有注册
  2. 绑定接口错误
  3. 方法名不对
  4. 返回类型不对
  5. maven导出遇到问题

2、CRUD

2.1、namespace

namespace中的包名要和接口中的包名相同

2.2、select

选择,查询语句

  • id:就是对应的namespace中的方法名;
  • resultType:sql语句执行的返回值类型
  • parameterType:参数类型
  1. 编写接口

    // 根据ID查询用户
    User getUserById(int id);
    
  2. 编写对应的mapper中的sql语句

    <select id="getUserById" parameterType="int" resultType="com.bin.pojo.User">
        select * from mybatis.user where id = #{id};
    </select>
    
  3. 测试

    @Test
    public void getUserById(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.getUserById(1);
        System.out.println(user);
        sqlSession.close();
    }
    

2.3、insert

<!--插入一个用户/对象中的属性可以直接取出-->
<insert id="addUser" parameterType="com.bin.pojo.User">
    insert into mybatis.user (id, name, pwd) values(#{id},#{name},#{pwd});
</insert>

2.4、update

<!--修改用户-->
<update id="UpdateUser" parameterType="com.bin.pojo.User">
    update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id};
</update>

2.5、delete

<!--删除一个用户-->
<delete id="deleteUser" parameterType="int">
    delete from mybatis.user where id=#{id};
</delete>

注意:

  • 增删改需要提交事务,否则不会对数据库进行操作

2.6、分析错误

  • 标签不要匹配错误
  • resource绑定mapper,需要使用路径
  • 程序配置文件必须符合规范
  • NullPointerException没有注册到资源
  • 输出的xml文件中存在中文乱码问题
  • maven资源没有导出

2.7、Map传递参数

  1. 接口:

    int UpdateUserPwd(Map<String,Object> map);
    
  2. Mapper.xml配置:

    <!--修改密码-->
    <update id="UpdateUserPwd" parameterType="map">
        update mybatis.user set pwd=#{password} where id=#{id};
    </update>
    
  3. 测试:

    @Test
    public void UpdateUserPwd(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("password","qweasd");
        map.put("id",6);
        int i = mapper.UpdateUserPwd(map);
        if(i>0){
            System.out.println("修改成功");
            sqlSession.commit();
        }
        sqlSession.close();
    }
    

    优点: 如果一个表中的字段非常多而需要的字段只有少数时,new一个实体对象显然很麻烦,需要对所有的字段都进行一次赋值。使用map传值可以更方便的实现需要进行的操作。如:修改用户密码时,只需要传入id和密码即可,而无需new一个用户对象。

2.8、mybatis的模糊查询

方式一:

手动添加"%"通配符

  • xml配置:
<!--模糊查询-->
<select id="fuzzyQuery" resultType="com.bin.pojo.Book">
    select * from mybatis.book where bookName like #{info};
</select>
  • 测试:
@Test
public void fuzzyQuery(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    BookMapper mapper = sqlSession.getMapper(BookMapper.class);
    List<Book> books = mapper.fuzzyQuery("%萨%");
    for (Book book : books) {
        System.out.println(book);
    }
    sqlSession.close();
}

说明: 需要手动添加"%"通配符,显然这种方式很麻烦,并且如果忘记添加通配符的话就会变成普通的查询语句,匹配全部字符查询。

  • 缺点:
    • 麻烦
    • 易出错
方式二:

在xml配置文件中添加"%"通配符,拼接字符串形式

<select id="fuzzyQuery" resultType="com.bin.pojo.Book">
    select * from mybatis.book where bookName like '%${info}%';
</select>

说明: 在mapper.xml配置文件中添加"%"通配符,但是需要用单引号将其包裹住,但是用单引号裹住之后#{}就无法被识别,要改成${}这种拼接字符串的形式。虽然通过方式二优化了方式一的缺点,但同时也造成了SQL安全性的问题,也就是用户可以进行SQL注入。

  • 缺点:
    • 不安全,可进行SQL注入
方式三:

在xml配置文件中添加"%"通配符,借助mysql函数

<select id="fuzzyQuery" resultType="com.bin.pojo.Book">
    select * from mybatis.book where bookName like 
    concat('%',#{info},'%');
</select>

说明: 解决了SQL注入且能在配置文件中写"%"通配符的问题,完美实现了模糊查询

  • 优点:
    • 安全
    • 方便
方式四:

与方式三一样使用mysqk函数,但使的用是${}形式,不过需要用单引号包裹住

<select id="fuzzyQuery" resultType="com.bin.pojo.Book">
    select * from mybatis.book where bookName like 
    concat('%','${info}','%');
</select>
总结:
  • #{}是预编译处理,mybatis在处理#{}时,会将其替换成"?",再调用PreparedStatement的set方法来赋值。
  • ${}是拼接字符串,将接收到的参数的内容不加任何修饰的拼接在SQL语句中,会引发SQL注入问题。

3、配置解析

3.1、核心配置

  • MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息
configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)

3.2、环境配置(environment)

MyBatis可以配置成适应多种环境

尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。

  • Mybatis默认的事务管理器是JDBC

  • 连接池:POOLED

3.3、属性(properties)

可以通过properties属性来实现引用配置文件

这些属性可以在外部进行配置,并可以进行动态替换。可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。【db.properties 】

  • 编写一个配置文件db.properties

    driver=com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode&amp;characterEncodeing=UTF-8
    username=root
    password=
    
  • 在核心配置文件中引入外部配置文件

    <!--引入外部配置文件-->
    <properties resource="db.properties">
        <property name="username" value="root"/>
    </properties>
    
  • 可以直接引入外部文件

  • 可以在其中增一些属性配置

  • 如果两个文件有相同的name字段,优先使用外部配置文件的

3.4、类型别名(typeAliases)

1、类取别名
  • 类型别名是java类型设置一个短的名字
  • 存在的意义仅在于用来减少类完全限定名的冗余
<!--可以给实体类取别名-->
<typeAliases>
    <typeAlias type="com.bin.pojo.User" alias="User"/>
    <typeAlias type="com.bin.pojo.Book" alias="Book"/>
</typeAliases>
2、指定包

也可以指定一个包名,mybatis在包名下面搜索需要的javaBean

没有注解时,它的默认别名为这个类的类名,首字母小写;

<typeAliases>
    <package name="com.bin.pojo"/>
</typeAliases>

若有注解,则别名为其注解值。

@Alias("author")
public class Author {
    ...
}

  • 在实体类较少的时候,可以使用给类取别名

  • 在实体类十分多时,可以使用指定包

3.5、设置(settings)

mybatis中极为重要的调整设置,会改变mybatis的运行行为

设置名描述有效值默认值
logImpl指定 MyBatis 所用日志的具体实现,未指定时将自动查找。SLF4J |LOG4J |LOG4J2 |JDK_LOGGING |COMMONS_LOGGING |STDOUT_LOGGING |NO_LOGGING未设置
cacheEnabled全局性地开启或关闭所有映射器配置文件中已配置的任何缓存。true |falsetrue
lazyLoadingEnabled延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 特定关联关系中可通过设置 fetchType 属性来覆盖该项的开关状态。true |falsefalse

3.6、其他配置

  • typeHandlers(类型处理器)
  • objectFactory(对象工厂)
  • plugins(插件)
    • mybatis-generator-core
    • mybatis-plus
    • 通用mapper

3.7、映射器(mappers)

MapperRegistry:注册绑定我们的Mapper文件

方式一:使用resource绑定注册

<mappers>
    <mapper resource="com/bin/dao/UserMapper.xml"/>
</mappers>

方式二:使用class文件绑定注册

<mappers>
    <mapper class="com.bin.dao.UserMapper"/>
</mappers>

注意点:

  • 接口和Mapper文件必须同名
  • 接口和Mapper文件必须同包

方式三:使用扫描包注入绑定

<mappers>
    <package name="com.bin.dao"/>
</mappers>

注意点:

  • 接口和Mapper文件必须同名
  • 接口和Mapper文件必须同包

3.8、生命周期和作用域

在这里插入图片描述

生命周期和作用域是至关重要的,因为错误的使用会导致非常严重的并发问题

SqlSessionFactoryBuilder:

  • 一旦创建SqlSessionFactory就不需要它了
  • 局部变量

SqlSessionFactory:

  • 可以看成数据库连接池
  • 一旦被创建就应该在应用运行期间一直存在,没有任何理由丢弃或者重新创建另一个实例
  • SqlSessionFactory的最佳作用域是应用作用域
  • 简单的是使用单例模式或者静态单例模式

SqlSession:

  • 相当于连接到连接池的一个请求
  • SqlSession的实例不是线程安全的,所以不能被共享
  • 它的最佳作用域是请求或方法作用域
  • 用完之后需关闭,否则会浪费资源

SqlSessionFactory可以创建多个SqlSession,每个sqlSession都可以创建多个Mapper

一个Mapper代表着一个具体的业务

在这里插入图片描述

4、解决属性名和字段名不一致的问题

4.1、不一致问题

数据库中的字段

在这里插入图片描述

实体类的属性

public class Book_02 {
    private int id;
    private String name;
    private String author;
}

测试出现错误

在这里插入图片描述

解决方法:

  • 起别名

    <select id="getBookById" resultType="book_02">
        select id, bookName as name, author from book where id=#{id};
    </select>
    

4.2、resultMap

结果集映射

数据库		id		bookName	author
实体类		id		name		author

mapper.xml配置:

<mapper namespace="com.bin.dao.Book_02Mapper">
    <!--结果集映射-->
    <resultMap id="bookMap" type="book_02">
        <!--colnum是数据库中的字段,property是实体类的属性-->
        <result column="id" property="id"/>
        <result column="bookName" property="name"/>
        <!--字段一致可以不做映射-->
        <!--<result column="author" property="author"/>-->
    </resultMap>
    
    <!--按id查询书籍-->
    <select id="getBookById" resultMap="bookMap">
        select * from mybatis.book where id=#{id};
    </select>
</mapper>
  • resultMap 元素是 MyBatis 中最重要最强大的元素
  • ResultMap 的设计思想是
    • 对简单的语句做到零配置
    • 对于复杂一点的语句,只需要描述语句之间的关系就行了
  • 一样的字段可以不做映射

5、日志

5.1、日志工厂

日志是查找错误的好助手

  • SLF4J
  • LOG4J
  • LOG4J2
  • JDK_LOGGING
  • COMMONS_LOGGING
    • STDOUT_LOGGING⭐ 标准日志输出
  • NO_LOGGING

在mybatis中具体使用哪一个日志实现,在mybatis核心配置文件中设置

<settings>
    <setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>

5.2、LOG4J

  • LOG4J是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件
  • 可以控制每一条日志的输出格式
  • 通过定义每一条日志信息的级别,能够更加细致地控制日志的生成过程
  • 通过一个配置文件来灵活地进行配置,而不需要修改应用的代码
  1. 导入LOG4J的包

    <!-- https://mvnrepository.com/artifact/log4j/log4j -->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    
  2. log4j.properties配置

    #将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
    log4j.rootLogger=DEBUG,console,file
    #控制台输出的相关设置
    log4j.appender.console = org.apache.log4j.ConsoleAppender
    log4j.appender.console.Target = System.out
    log4j.appender.console.Threshold=DEBUG
    log4j.appender.console.layout = org.apache.log4j.PatternLayout
    log4j.appender.console.layout.ConversionPattern=[%c]-%m%n
    #文件输出的相关设置
    log4j.appender.file = org.apache.log4j.RollingFileAppender
    log4j.appender.file.File=./log/bin.log
    log4j.appender.file.MaxFileSize=10mb
    log4j.appender.file.Threshold=DEBUG
    log4j.appender.file.layout=org.apache.log4j.PatternLayout
    log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n
    #日志输出级别
    log4j.logger.org.mybatis=DEBUG
    log4j.logger.java.sql=DEBUG
    log4j.logger.java.sql.Statement=DEBUG
    log4j.logger.java.sql.ResultSet=DEBUG
    log4j.logger.java.sql.PreparedStatement=DEBUG
    
  3. 配置log4j为日志实现

    <settings>
        <setting name="logImpl" value="LOG4J"/>
    </settings>
    
  4. log4j的使用,直接测试运行查询

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

5.3、简单使用

  1. 在使用Log4j的类中,导入包import org.apache.log4j.Logger;

  2. 日志对象,参数为当前类的class

    static Logger logger = Logger.getLogger(UserMapperTest.class);
    
  3. 日志级别

    logger.info("info:进入了testLog4j");
    logger.debug("debug:进入了testLog4j");
    logger.error("error:进入了testLog4j");
    

6、使用mybatis实现分页

6.1、使用Limit分页

  1. 接口

    // 分页
    List<User> getUserByLimit(Map<String,Integer> map);
    
  2. Mapper.xml

    <!--分页-->
    <select id="getUserByLimit" parameterType="map" resultType="user">
        select * from mybatis.user limit #{startIndex},#{pageSize}
    </select>
    
  3. 测试

    @Test
    public void getUserByLimit(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        map.put("startIndex",1);
        map.put("pageSize",5);
        List<User> users= mapper.getUserByLimit(map);
        for (User user : users) {
            logger.info("分页查询用户:" + user);
        }
        sqlSession.close();
    }
    

6.2、RewBounds分页

  1. 接口

    // 分页2
    List<User> gteUserByRowBounds();
    
  2. Mapper.xml

    <!--分页2-->
    <select id="gteUserByRowBounds" resultMap="UserMap">
        select * from mybatis.user;
    </select>
    
  3. 测试

    @Test
    public void gteUserByRowBounds(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
    
        // RowBounds实现
        RowBounds rowBounds = new RowBounds(1, 2);
    
        List<User> users = sqlSession.selectList(
            "com.bin.dao.UserMapper.gteUserByRowBounds", null, rowBounds);
        for (User user : users) {
            logger.info("分页2查询:" + user);
        }
        sqlSession.close();
    }
    

6.3、分页插件

7、使用注解开发

7.1、面向接口编程

之前学到的都是面向对象编程,也学习过接口,但在真正开发中,很多时候我们会选择面向接口编程;
根本原因 : 解耦、可扩展、提高复用,分层开发中,上层不用管具体的实现,大家都遵守共同的标准,使得开发变得更容易,规范性更好
在一个面向对象的系统中,系统的各种功能是由许许多多的不同对象协作完成的,在这种情况下,各个对象内部是如何实现的,对系统设计人员来讲是不那么重要的;
而各个对象之间的协作关系则成为系统设计的关键。小到不同类之间的通信,大到各模块之间的交互,在系统设计之初都是要着重考虑的,这也是系统设计的主要工作内容。面向接口编程就是按照这种思想来编程。

关于接口的理解

  • 接口从更深层次的理解,应是定义(规范,约束)与实现(名实分离的原则)的分离。
  • 接口的本身反映了系统设计人员对系统的抽象理解。
  • 接口应有两类:
  • 第一类是对一个个体的抽象,它可对应为一个抽象体(abstract class);
  • 第二类是对一个个体某一方面的抽象,即形成一个抽象面(interface);
  • 一个体有可能有多个抽象面。抽象体与抽象面是有区别的。

三个面向区别

  • 面向对象是指,我们考虑问题时,以对象为单位,考虑它的属性及方法 .
  • 面向过程是指,我们考虑问题时,以一个具体的流程(事务过程)为单位,考虑它的实现 .
  • 接口设计与非接口设计是针对复用技术而言的,与面向对象(过程)不是一个问题.更多的体现就是对系统整体的架构

7.2、使用注解开发

  1. 注解在接口上实现

    // 使用注解查询
    @Select("select * from user")
    List<User> getUsers();
    
  2. 需要在核心文件中绑定接口

    <mappers>
    	<mapper class="com.bin.dao.UserMapper"/>
    </mappers>
    
  3. 测试

    @Test
    public void getUsers(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> users = mapper.getUsers();
        for (User user : users) {
            logger.info("使用注解查询:" + user);
        }
    }
    

本质:反射机制实现

底层:动态代理

**Mybatis详细的执行流程!**⭐

7.3、CRUD

在工具类创建的时候可以实现自动提交

publicstaticSqlSession  getSqlSession(){
    return sqlSessionFactory.openSession(true);}
  • 编写接口

    public interface UserMapper02 {
        @Select("select * from user")
        List<User> getUsers();
    
        @Select("select * from user where id = #{id}")
        List<User> getUserById(@Param("id") int id);
    
        @Insert("insert into user(id,name,pwd) values(#{id},#{name},#{pwd})")
        int addUser(User user);
    
        @Update("update user set name=#{name},pwd=#{pwd} where id=#{id}")
        int updateUser(User user);
    
        @Delete("delete from user where id = #{id}")
        int deleteUser(@Param("id") int id);
    }
    
  • 将接口注册绑定到核心文件中

    <mapper class="com.bin.dao.UserMapper02"/>
    

关于@Param()注解

  • 基本类型的参数或String类型需要使用
  • 引用类型不需要
  • 只有一个基本类型可以忽略不写,但建议写上
  • SQL中引用的是@Param()注解中设定的属性名

#{}和${}的区别:

  • #{} 预编译,可避免SQL注入
  • ${} 拼接字符串,可以被进行SQL注入

8、Lombok

  • java library
  • plugs
  • build tools
  • with one annotation your class
  1. 在IDEA中安装Lombok插件

  2. 在项目中导入Lombok的jar包

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.20</version>
        <scope>provided</scope>
    </dependency>
    
  3. 在实体类上加注解

    @Getterand@Setter
    @FieldNameConstants
    @ToString
    @EqualsAndHashCode
    @AllArgsConstructor,
    @RequiredArgsConstructor and @NoArgsConstructor
    @Log,@Log4j,@Log4j2,@Slf4j,@XSlf4j,@CommonsLog,@JBossLog,@Flogger
    @Data
    @Builder
    @Singular
    @Delegate
    @Value
    @Accessors
    @Wither
    @SneakyThrows
    
    • @Data 无参构造、get、set、toString、equals、hashcode
    • @AllArgsConstructor 有参构造
    • @NoArgsConstructor 无参构造

9、多对一处理

9.1、编写SQL,创建数据库表

CREATE TABLE `teacher` (
  `id` INT(10) NOT NULL,
  `name` VARCHAR(30) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT INTO teacher(`id`, `name`) VALUES (1, '秦老师'); 
CREATE TABLE `student` (
  `id` INT(10) NOT NULL,
  `name` VARCHAR(30) DEFAULT NULL,
  `tid` INT(10) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fktid` (`tid`),
  CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES (1, '小明', 1); 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES (2, '小红', 1); 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES (3, '小张', 1); 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES (4, '小李', 1); 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES (5, '小王', 1);

9.2、测试环境搭建

  1. 导入lombok
  2. 创建javaBean
  3. 建立Mapper接口
  4. 建立Mapper.xml文件
  5. 在核心配置文件中绑定mapper接口或配置文件
  6. 测试查询

9.3、按照查询嵌套处理

<select id="getStudents" resultMap="StudentsTeacher">
    select * from mybatis.student;
</select>

<resultMap id="StudentsTeacher" type="student">
    <result property="id" column="id"/>
    <result property="name" column="name"/>
<--属性中的引用对象单独处理,对象:association,集合:collection-->
    <association property="teacher" column="tid" javaType="teacher" select="getTeacher"/>
</resultMap>

<select id="getTeacher" resultType="teacher">
    select * from mybatis.teacher where id = #{tid};
</select>

9.4、按照结果嵌套处理

<select id="getStudentList" resultMap="StudentsTeacher2">
    select s.id as sid,s.name as sname,s.tid as tid, t.name as tname
    from mybatis.student s
    join mybatis.teacher t
    on s.tid = t.id;
</select>

<resultMap id="StudentsTeacher2" type="student">
    <result property="id" column="sid"/>
    <result property="name" column="sname"/>
    <association property="teacher" javaType="teacher">
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>
    </association>
</resultMap>

多对一查询方式:

  • 子查询
  • 联表查询

10、一对多处理

创建javaBean

public class Student {
    private int id;
    private String name;
    private int tid;
}

public class Teacher {
    private int id;
    private String name;
    private List<Student> students;
}

10.1、按照查询嵌套处理

<select id="getTeacherById02" resultMap="teacherStuden02">
    select * from mybatis.teacher;
</select>

<resultMap id="teacherStuden02" type="teacher">
    <collection property="students" javaType="ArrayList" ofType="student" column="id" select="getStudent"/>
</resultMap>

<select id="getStudent" resultType="student">
    select * from mybatis.student where tid = #{id}
</select>

### 10.2、按照结果嵌套处理

​```xml
<select id="getTeacherById" resultMap="teacherStudent">
    select t.id as tid,t.name as tname,s.id as sid,s.name as sname
    from mybatis.teacher t join mybatis.student s
    on t.id = s.tid
    where t.id = #{id}
</select>

<resultMap id="teacherStudent" type="teacher">
    <id property="id" column="tid"/>
    <result property="name" column="tname"/>
    <collection property="students" ofType="student">
        <id property="id" column="sid"/>
        <result property="name" column="sname"/>
        <result property="tid" column="tid"/>
    </collection>
</resultMap>

**小结:**

1. 关联(对象):association	【多对一】
2. 集合:collection     【一对多】
3. javaType  用来指定实体类中的属性类型
4. ofType  用来指定映射到List或集合中的pojo类型,泛型中约束的类型

**注意点:**

- 保证SQL可读性,尽量保证通俗易懂
- 注意一对多和多对一中属性名和字段的问题
- 若错误不好排查,可以使用日志,建议使用Log4j

**面试高频:**

- MySQL引擎
- innoDB底层原理
- 索引
- 索引优化

11、动态SQL

动态SQL是根据不同条件来生成不同的SQL语句

11.1、编写SQL,创建数据库表

CREATE TABLE `blog`(
`id` VARCHAR(50) NOT NULL COMMENT '博客id',
`title` VARCHAR(100) NOT NULL COMMENT '博客标题',
`author` VARCHAR(30) NOT NULL COMMENT '博客作者',
`create_time` DATETIME NOT NULL COMMENT '创建时间',
`views` INT(30) NOT NULL COMMENT '浏览量'
)ENGINE=INNODB DEFAULT CHARSET=utf8;

11.2、测试环境搭建

  1. 导包

  2. 创建javaBean

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Blog {
        private String id;
        private String title;
        private String author;
        private Date createTime;
        private int views;
    }
    
  3. 建立Mapper接口

    int addBlog(Blog blog);
    
    List<Blog> queryBlogIF(Map map);
    
    List<Blog> queryBlogChoose(Map map);
    
    List<Blog> queryBlogTrim(Map map);
    
    int updateBlogTrim(Map map);
    
    List<Blog> queryBlogForeach(Map map);
    
  4. 建立Mapper.xml文件

    <select id="queryBlogIF" parameterType="map" resultType="blog">
        select * from mybatis.blog
        <where>
            <if test="title != null">
                title = #{title}
            </if>
            <if test="author != null">
                and author = #{author}
            </if>
        </where>
    </select>
    
  5. 在核心配置文件中绑定mapper接口或配置文件

  6. 测试查询

11.3、IF

<select id="queryBlogIF" parameterType="map" resultType="blog">
    select * from mybatis.blog
    <where>
        <if test="title != null">
            title = #{title}
        </if>
        <if test="author != null">
            and author = #{author}
        </if>
    </where>
</select>

11.4、choose

<select id="queryBlogChoose" parameterType="map" resultType="blog">
    select * from mybatis.blog where
    <choose>
        <when test="title != null">
            title = #{title}
        </when>
        <when test="author">
            author = #{author}
        </when>
        <otherwise>
            views = #{views}
        </otherwise>
    </choose>
</select>

11.5、set

<update id="updateBlogTrim" parameterType="map">
    update mybatis.blog
    <set>
        <if test="title != null">
            title = #{title},
        </if>
        <if test="author != null">
            author = #{author},
        </if>
        <if test="views != null">
            views = #{views}
        </if>
    </set>
    where id = #{id};
</update>

11.6、trim

<update id="updateBlogTrim" parameterType="map">
    update mybatis.blog
    <trim prefix="set" suffixOverrides=",">
        <if test="title != null">
            title = #{title},
        </if>
        <if test="author != null">
            author = #{author},
        </if>
        <if test="views != null">
            views = #{views}
        </if>
    </trim>
    where id = #{id};
</update>

<select id="queryBlogTrim" parameterType="map" resultType="blog">
    select * from mybatis.blog
    <trim prefix="WHERE" prefixOverrides="AND |OR ">
        <if test="title != null">
            title = #{title}
        </if>
        <if test="author != null">
            and author = #{author}
        </if>
    </trim>
</select>

总结:

where元素在子元素存在(有值)的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。

11.7、SQL片段

  1. 使用sql标签

    <sql id="if-title-author">
        <if test="title != null">
            title = #{title}
        </if>
        <if test="author != null">
            and author = #{author}
        </if>
    </sql>
    
  2. 在需要使用的地方使用include标签引用

    <select id="queryBlogIF" parameterType="map" resultType="blog">
        select * from mybatis.blog
        <where>
            <include refid= "if-title-author"/>
        </where>
    </select>
    

注意事项:

  • 最好基于单表来定义sql片段
  • 不要存在where标签

11.8、forEach

<select id="queryBlogForeach" parameterType="map" resultType="blog">
    select * from mybatis.blog
    <where>
<!--        
        id in
        <foreach collection="ids" item="id" open="(" separator="," close=")">
            #{id}
        </foreach>
-->
        <foreach collection="ids" item="id"  separator="or">
            id = #{id}
        </foreach>
    </where>
</select>
@Test
public void queryBlogForeach(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
    Map<String,List> map = new HashMap<String, List>();
    List<Integer> list = new ArrayList<Integer>();
    list.add(1);
    list.add(3);
    list.add(4);
    map.put("ids",list);
    List<Blog> blogs = mapper.queryBlogForeach(map);
    for (Blog blog : blogs) {
        logger.info("动态SQL-foreach:" + blog);
    }
    sqlSession.close();
}

12、缓存

12.1、简介

查询: 连接数据库,耗资源!一次查询的结果,给他暂存在一个可以直接取到的地方!–》内存:缓存我们再次查询相同数据的时候,直接走缓存,就不用走数据库了

  1. 什么是缓存 [ Cache ]?
    • 存在内存中的临时数据。
    • 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题。
  2. 为什么使用缓存?
    • 减少和数据库的交互次数,减少系统开销,提高系统效率。
  3. 什么样的数据能使用缓存?
    • 经常查询并且不经常改变的数据。【可以使用缓存】

12.2、mybatis缓存

  • MyBatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率。
  • MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存
    • 默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)
    • 二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
    • 为了提高扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存

12.3、一级缓存

  • 一级缓存也叫本地缓存: SqlSession
    • 与数据库同一次会话期间查询到的数据会放在本地缓存中。
    • 以后如果需要获取相同的数据,直接从缓存中拿,没必须再去查询数据库;

测试步骤:

  1. 开启日志!
  2. 测试在一个Sesion中查询两次相同记录
  3. 查看日志输出

缓存失效的情况:

  1. 查询不同的东西

    @Test
    public void queryUserById(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.queryUserById(1);
        logger.info("一级缓存:" + user);
        User user1 = mapper.queryUserById(2);
        logger.info("一级缓存:" + user1);
        logger.info("一级缓存:" + (user == user1));
        sqlSession.close();
    }
    

在这里插入图片描述

  1. 增删改操作,可能会改变原来的数据,所以必定会刷新缓存!

    @Test
    public void queryUserById(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.queryUserById(1);
        logger.info("一级缓存:" + user);
        mapper.updateUser(new User(2,"张三","123456"));
        User user1 = mapper.queryUserById(1);
        logger.info("一级缓存:" + user1);
        logger.info("一级缓存:" + (user == user1));
        sqlSession.close();
    }
    ```![在这里插入图片描述](https://img-blog.csdnimg.cn/20210716094934950.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0Fkb2JlX2phdmE=,size_16,color_FFFFFF,t_70#pic_center)
    
    
    
  2. 查询不同的Mapper.xml

  3. 手动清理缓存!

    @Test
    public void queryUserById(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.queryUserById(1);
        logger.info("一级缓存:" + user);
        // 清除缓存
        sqlSession.clearCache();
        User user1 = mapper.queryUserById(1);
        logger.info("一级缓存:" + user1);
        logger.info("一级缓存:" + (user == user1));
        sqlSession.close();
    }
    

在这里插入图片描述

小结: 一级缓存默认是开启的,只在一次SqlSession中有效,也就是拿到连接到关闭连接这个区间段!一级缓存就是一个Map。

12.4、二级缓存

  • 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
  • 基于namespace级别的缓存,一个名称空间,对应一个二级缓存;
  • 工作机制
    • 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中;
    • 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中;
    • 新的会话查询信息,就可以从二级缓存中获取内容;
    • 不同的mapper查出的数据会放在自己对应的缓存(map)中;

步骤:

  1. 开启全局缓存

    <!--显示的开启全局缓存-->
    <setting name="cacheEnabled" value="true"/>
    
  2. 在要使用二级缓存的Mapper中开启

    <!--在当前mapper.xml中使用二级缓存-->
    <cache/>
    
  3. 也可以自定义参数

    <!--在当前Mapper.xml中使用二级缓存-->
    <cache
           eviction="FIFO"
           flushInterval="60000"
           size="512"
           readOnly="true"/>
    
  4. 测试

    @Test
    public void queryUserById(){
    SqlSession sqlSession1 = MybatisUtils.getSqlSession();
    SqlSession sqlSession2 = MybatisUtils.getSqlSession();
    UserMapper mapper1 = sqlSession1.getMapper(UserMapper.class);
    UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);
    
    User user1 = mapper1.queryUserById(1);
    logger.info("一级缓存:" + user1);
    
    sqlSession1.close();
    User user2 = mapper2.queryUserById(1);
    logger.info("一级缓存:" + user1);
    logger.info("一级缓存:" + (user1 == user2));
    sqlSession2.close();
    }
    

在这里插入图片描述

问题: 我们需要将实体类序列化!否则就会报错!

Caused by: java.io.NotSerializableException: com.bin.pojo.User

小结:

  • 只要开启了二级缓存,在同一个Mapper下就有效
  • 所有的数据都会先放在一级缓存中;
  • 只有当会话提交,或者关闭的时候,才会提交到二级缓冲中!

12.5、缓存原理

在这里插入图片描述

12.6、自定义缓存-ehcache

Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存

要在程序中使用ehcache,先要导包!

<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
<dependency>
    <groupId>org.mybatis.caches</groupId>
    <artifactId>mybatis-ehcache</artifactId>
    <version>1.1.0</version>
</dependency>

在mapper中指定使用我们的ehcache缓存实现!

<!--在当前Mapper.xml中使用二级缓存-->
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>

ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"         updateCheck="false">
    <!--       
    diskStore:为缓存路径,ehcache分为内存和磁盘两级,此属性定义磁盘的缓存位置。参数解释如下:       
    user.home – 用户主目录       
    user.dir  – 用户当前工作目录      
    java.io.tmpdir – 默认临时文件路径     
    -->    
    <diskStore path="./tmpdir/Tmp_EhCache"/>        
    <defaultCache            
	    eternal="false"            
	    maxElementsInMemory="10000"            
	    overflowToDisk="false"            
	    diskPersistent="false"            
	    timeToIdleSeconds="1800"            
	    timeToLiveSeconds="259200"            
	    memoryStoreEvictionPolicy="LRU"/>     
    <cache            
    	name="cloud_user"            
    	eternal="false"            
    	maxElementsInMemory="5000"            
    	overflowToDisk="false"            
    	diskPersistent="false"            
    	timeToIdleSeconds="1800"            
    	timeToLiveSeconds="1800"            
    	memoryStoreEvictionPolicy="LRU"/>    
    <!--       
    	defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策略。只能定义一个。     
    -->    
    <!--      
        name:缓存名称。      
        maxElementsInMemory:缓存最大数目      
        maxElementsOnDisk:硬盘最大缓存个数。      
        eternal:对象是否永久有效,一但设置了,timeout将不起作用。      
        overflowToDisk:是否保存到磁盘,当系统当机时      
        timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。      
        timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。      
        diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.      
        diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。      
        diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。      
        memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。      
        clearOnFlush:内存数量最大时是否清除。      
        memoryStoreEvictionPolicy:可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。      
        FIFO,first in first out,这个是大家最熟的,先进先出。      
        LFU, Less Frequently Used,就是上面例子中使用的策略,直白一点就是讲一直以来最少被使用的。如上面所讲,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。      
        LRU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。   
        -->
</ehcache>

点击下方链接可以阅读其他模块的笔记喔

spring 学习笔记1
狂神自学网 mybatis 学习总结

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值