mybatis

Mybatis

1. 简介

1.1 什么是mybatis

  • MyBatis 是一款优秀的持久层框架

  • 它支持自定义 SQL、存储过程以及高级映射。

  • MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。

  • MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

  • MyBatis 本是apache的一个开源项目iBatis,

  • 2010年这个项目由apache software foundation 迁移到了[google code](https://baike.baidu.com/item/google code/2346604),并且改名为MyBatis 。

  • 2013年11月迁移到Github

如何获得mybatis?

  1. GitHub:https://github.com/mybatis/mybatis-3/releases

  2. maven仓库

    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.2</version>
    </dependency>
    
    
  3. 中文文档:https://mybatis.org/mybatis-3/zh/index.html

1.2 持久层

2. 第一个Mybatis程序

思路:搭建环境—>导入Mybatis—>编写代码—>测试!

2.1 搭建环境

搭建数据库

CREATE DATABASE `mybatis`;
USE `mybatis`;

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

INSERT `user`(`id`,`name`,`pwd`) VALUES
(1,'poppy','123456'),
(2,'张三','123456'),
(3,'李四','123456')
  • 新建一个普通的maven项目

  • 删除src目录 方便建立子工程

  • 导入依赖

     <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.11</version>
            </dependency>
        </dependencies>
    

2.2 创建一个模块

  • 编写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>
    <!--环境 可以有多个 有默认的-->
        <environments default="development">
    <!--具体的driver url username password-->
            <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=true&amp;characterEncoding=UTF-8"/>
                    <property name="username" value="root"/>
                    <property name="password" value="304430"/>
                </dataSource>
            </environment>
        </environments>
    
    <!--    注册mapper-->
    <!--    每一个mapper类对应一个mapper-->
        <mappers>
    
        </mappers>
    </configuration>
    
  • 编写mybatis的工具类

    package com.poppy.utils;
    
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    
    import java.io.IOException;
    import java.io.InputStream;
    
    // 从配置文件中获取 工厂 ---> SqlSessionFactory
    public class MybatisUtils {
        // 提升作用域 下边方法会用不到
        private static SqlSessionFactory sqlSessionFactory;
    
        static{
            try {
                String resource = "mybatis-config.xml";
                InputStream inputStream = Resources.getResourceAsStream(resource);
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        // 获取SqlSession对象
        // SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
        // 你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句
        public static SqlSession getSqlSession(){
            return sqlSessionFactory.openSession();
        }
    }
    

2.3 编写代码

  • 实体类

  • 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 命名空间  一个对应一个mapper-->
    <mapper namespace="com.poppy.mappper.UserMapper">
    <!--    id 方法名  resultType 返回值 一般使用 resultType resultMap-->
        <select id="getUserList" resultType="com.poppy.pojo.User">
            select * from mybatis.user
        </select>
    </mapper>
    
  • 注册mapper

    注意 路径以“/”结尾

        <mappers>
    		<!--maven 导出资源问题-->
            <mapper resource="com/poppy/mappper/UserMapper.xml"/>
        </mappers>
    

2.4 测试

  • junit 测试
package com.poppy.pojo;

import com.poppy.mappper.UserMapper;
import com.poppy.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class UserMapperTest {
    /*
    1. 第一步获取sqlSession对象
    2. 第二步获取mapper对象
    3. 关闭sqlSession
     */
    @Test
    public void test(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        try{
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            List<User> userList = mapper.getUserList();
            for (User user : userList) {
                System.out.println(user);
            }
        }finally {
            sqlSession.close();
        }
    }
}

2.5 注意点

  1. 配置文件没有注册

    <mappers>
        <!--maven 导出资源问题-->
        <mapper resource="com/poppy/mappper/UserMapper.xml"/>
    </mappers>
    
  2. 绑定接口错误

    <mapper namespace="com.poppy.mappper.UserMapper">
    <!--id 方法名  resultType 返回值 一般使用 resultType resultMap-->
        <select id="getUserList" resultType="com.poppy.pojo.User">
            select * from mybatis.user
        </select>
    </mapper>
    
  3. 方法名不对

  4. 返回类型不对

  5. 资源导出问题

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>
    

3. CRUD

1. mapper里边的参数含义

<select id="getUserByID" parameterType="int" resultType="com.poppy.pojo.User">
    select * from mybatis.user where id = #{id}
</select>
  1. id 对应的方法名
  2. parameterType 参数类型
  3. 返回结果类型

2. Select

<select id="getUserList" resultType="com.poppy.pojo.User">
    select * from mybatis.user
</select>

<select id="getUserByID" parameterType="int" resultType="com.poppy.pojo.User">
    select * from mybatis.user where id = #{id}
</select>
public void test(){
        // 第一步 获取SqlSession对象
        // 第二步 根据类的映射文件 拿到对应的mapper
        // 第三步 执行sql 方法名对应!
        SqlSession sqlSession = new MybatisUtils().getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.getUserList();
        for (User user : userList) {
            System.out.println(user);
        }
        sqlSession.close();
    }

3. Update

<update id="updateUser" parameterType="com.poppy.pojo.User">
    update mybatis.user
    set name = #{name}, pwd = #{pwd}
    where id = #{id};
</update>

4. Insert

<insert id="insertUser" parameterType="com.poppy.pojo.User">
    insert into mybatis.user (id, name, pwd) values (#{id}, #{name}, #{pwd});
</insert>

5. Delete

<delete id="deleteUser" parameterType="int">
    delete
    from mybatis.user
    where id = #{id};
</delete>

注意 增删改 需要提交事务

6. 万能Map

// 假设 表中字段很多 且修改 字段很少 则 不可能重新构建一个新用户
// 使用map传递参数
int updateUser2(Map<String, Object> map);
<update id="updateUser2" parameterType="map">
    update mybatis.user
    set name = #{name}
    where id = #{id};
</update>
public void updateUser2(){
    SqlSession sqlSession = new MybatisUtils().getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);

    Map<String, Object> map = new HashMap<>();

    map.put("id", 1);
    map.put("name", "manjuas");

    mapper.updateUser2(map);

    sqlSession.commit();
    sqlSession.close();
}

Map传递参数,直接在sql中取出key即可![parameterType=“map”]

对象传递参数,直接在sql中取出对象的属性即可![parameterType=“Object”]

只有一个基本类型的情况下,可以直接在sql中取到!(可以省略)

<select id="getUserByID" parameterType="int" resultType="com.poppy.pojo.User">

7. 模糊查询

两种方式 避免sql注入问题

  1. 传递参数时 传入通配符

    SqlSession sqlSession = new MybatisUtils().getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    
    List<User> users = mapper.getUserList2("李");
    for (User user : users) {
        System.out.println(user);
    }
    sqlSession.close();
    
  2. 在sql中固定通配符

select * from mybatis.user where name like "%"#{value}"%"

4. 配置解析

MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。

configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)

1. 环境配置(environments)

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

不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。

  • 每个数据库对应一个 SqlSessionFactory 实例
<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=true&amp;characterEncoding=UTF-8"/>
            <property name="username" value="root"/>
            <property name="password" value="304430"/>
        </dataSource>
    </environment>
    <environment id="test">
        <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=true&amp;characterEncoding=UTF-8"/>
            <property name="username" value="root"/>
            <property name="password" value="304430"/>
        </dataSource>
    </environment>
</environments>
  1. 默认使用的环境 ID(比如:default=“development”)。
  2. 每个 environment 元素定义的环境 ID(比如:id=“development”)。
  3. 事务管理器的配置(比如:type=“JDBC”)。
  4. 数据源的配置(比如:type=“POOLED”)。
  • 在 MyBatis 中有两种类型的事务管理器(也就是 type="[JDBC|MANAGED]"):
  • 有三种内建的数据源类型(也就是 type="[UNPOOLED|POOLED|JNDI]")
    • UNPOOLED 没有池子
    • POOLED 池子 默认数据源 提高速度 池子: 使用完可以回收
    • JNDI

2. 属性(properties)

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

注意点:

在xml文件中,标签由规定好的顺序!!!

请添加图片描述

两种方式

  1. 配置文件
driver = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/mybatis?useSSl=true&useUnicode=true&characterEncoding=UTF-8
username = root
password = 304430
  1. 标签内
<properties resource="db.properties">
    <property name="username" value="root"/>
    <property name="password" value="304430"/>
</properties>

当标签和配置文件中有重复元素 优先使用配置文件的!!!!

3. 类型别名(typeAliases)

  • 类型别名可为 Java 类型设置一个缩写名字。
  • 它仅用于 XML 配置,意在降低冗余的全限定类名书写。

两种方式

<!--为Java类型设置一个缩写名字-->
<typeAliases>
    <typeAlias type="com.poppy.pojo.User" alias="User"/>
</typeAliases>
<!--为Java类型设置一个缩写名字-->
<!--扫描包-->
<typeAliases>
    <package name="com.poppy.pojo"/>
</typeAliases>

第一种方式为用到的类设置别名,可以进行diy

第二种方式不能进行diy,提供实体类包的位置,别名默认为类名,首字母缩写。若要进行diy需要加注解

@Alias("User")
public class User {}

4. 设置(settings)

在这里插入图片描述

5. 其他设置

在这里插入图片描述

插件 plugins

在这里插入图片描述

  • [mybatis-generator-core]
  • mybatis-plus

6. 映射器(mappers)

方式一:

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

方式二:通过类

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

注意点:

  • 接口和他的Mapper配置文件必须同名!
  • 接口和他的Mapper配置文件在同一个包下!

方式三:

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

注意点:

  • 接口和他的Mapper配置文件必须同名!
  • 接口和他的Mapper配置文件在同一个包下!

7. 作用域(Scope)和生命周期

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

在这里插入图片描述

SqlSessionFactoryBuilder
  • 一旦创建了 SqlSessionFactory,就不再需要它了。
  • 局部变量
SqlSessionFactory
  • 说白了 可以想象成一个数据库连接池

  • SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在

  • SqlSessionFactory 的最佳作用域是应用作用域。

  • 最简单的就是使用单例模式或者静态单例模式。

  • 使用 SqlSessionFactory 的最佳实践是在应用运行期间不要重复创建多次 —> 英法严重的并发问题

SqlSession
  • 每个线程都应该有它自己的 SqlSession 实例。

  • SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域

  • 随用随关 不然资源会被占用

在这里插入图片描述

每一个Mapper就代表一个业务!

5. 解决属性名和字段名不一致的问题

1、问题

在这里插入图片描述

新建一个项目,数据库中的字段与实体类的属性名不一致的情况下进行测试

public class User {
    private int id;
    private String name;
    private String password;
}

测试出现问题

在这里插入图片描述

方式一:修改sql

<!--select id, name, pwd from mybatis.user where id = #{id}-->
<!--select * from mybatis.user where id = #{id}-->
<!--修改别名-->
<select id="getUserByID" parameterType="int" resultType="User">
    select id, name, pwd as password from mybatis.user where id = #{id}
</select>

在这里插入图片描述

2、resultMap

方式二:不修改sql 结果映射集!

id		id
name	name
pwd		password

在这里插入图片描述

mybatis-config.xml

<resultMap id="UserMap" type="User">
    <!--相同字段可以不用改-->
    <!--<id property="id" column="id"/>-->
    <!--<id property="name" column="name"/>-->
    <id property="password" column="pwd"/>
</resultMap>

<!--select id, name, pwd from mybatis.user where id = #{id}-->
<select id="getUserByID" parameterType="int" resultMap="UserMap">
    select * from mybatis.user where id = #{id}
</select>

查询成功

在这里插入图片描述

6. 日志

6.1、 日志工厂

如果一个数据库操作出现了异常,我们需要排错。日志就是最好的助手!

曾经:sout、debug

现在: 日志工厂!

mybatis 的设置配置日志

在这里插入图片描述

  • SLF4J
  • LOG4J 【掌握】
  • LOG4J2
  • JDK_LOGGING
  • COMMONS_LOGGING
  • STDOUT_LOGGING【掌握】
  • NO_LOGGING

STDOUT_LOGGING

标准的日志格式

直接配置即可使用

注意:

建议直接复制键值! 容易出错!

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

在这里插入图片描述

6.2、 log4j

什么是log4j

  • 控制日志信息输送的目的地是控制台、文件、GUI组件
  • 也可以控制每一条日志的输出格式
  • 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程
  • 最令人感兴趣的就是,这些可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。

使用log4j

  1. 导包

    <!-- 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.DailyRollingFileAppender
    log4j.appender.file.File = ./log/Poppy.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. mybatis-config.xml下边配置日志类别

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

运行结果
在这里插入图片描述

简单使用

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

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

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

public void jog4jTest(){
    logger.info("info:进入了jog4jTest方法");
    logger.debug("debug:进入了jog4jTest方法");
    logger.error("error:进入了jog4jTest方法");
}

7. 实现分页

7.1、 使用limit实现分页

limit 语法

select * from user limit startIndex, pageSize
  1. 接口

    List<User> getUsersByLimit(Map<String,Integer> map);
    
  2. mapper.xml

    <select id="getUsersByLimit" parameterType="map" resultMap="UserMap">
        select * from user limit #{startIndex},#{pageSize}
    </select>
    
  3. 测试

    public void getUsersByLimit(){
        SqlSession sqlSession = new MybatisUtils().getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    
        HashMap<String, Integer> map = new HashMap<>();
        map.put("startIndex", 0);
        map.put("pageSize", 2);
    
        List<User> users = mapper.getUsersByLimit(map);
        for (User user : users) {
            System.out.println(user);
        }
        
        sqlSession.close();
    }
    

小知识

select * from user limit startIndex, pageSize
-- 当pageSize为-1的时候,可以查出从startIndex到最后的所有信息
-- 当然 这个"bug "被修复了

7.2、 使用RowBounds对象实现(oop思想)

在这里插入图片描述

  1. 接口

    List<User> getUsersByRowBounds();
    
  2. xml

    <select id="getUsersByRowBounds" resultMap="UserMap">
        select * from user
    </select>
    
  3. 测试

    public void getUsersByRowBounds(){
        SqlSession sqlSession = new MybatisUtils().getSqlSession();
        // 不通过mapper执行sql
        // 参数需要一个rowBounds对象
        RowBounds rowBounds = new RowBounds(0, 2);
        List<User> users = sqlSession.selectList("com.poppy.dao.UserMapper.getUsersByRowBounds", null, rowBounds);
    
        for (User user : users) {
            System.out.println(user);
        }
    
        sqlSession.close();
    }
    

7.3、 分页插件

PageHelper

在这里插入图片描述

帮助文档

https://pagehelper.github.io/docs/howtouse/

8. 使用注解开发

8.1、面向接口编程

8.2、 使用注解开发

  1. 接口
@Select("select * from user")
List<User> getUsers();
  1. mappers注册

    <!--包和类都可以实现-->
    <mappers>
        <!--<mapper resource="com/poppy/dao/UserMapper.xml"/>-->
        <mapper class="com.poppy.dao.UserMapper"/>
        <!--<package name="com.poppy.dao"/>-->
    </mappers>
    
  2. 测试

    @Test
    public void getUsers(){
        SqlSession sqlSession = new MybatisUtils().getSqlSession();
        // 通过class 拿到UserMapper的所有属性 调用其方法 实现
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> users = mapper.getUsers();
        for (User user : users) {
            System.out.println(user);
        }
        sqlSession.close();
    }
    

局限性

  • 字段属性不一致 无法处理
  • sql复杂的情况下无法不建议使用 会显得更复杂 更乱
  • 使用注解来映射简单语句会使代码显得更加简洁
  • 但对于稍微复杂一点的语句,Java 注解不仅力不从心,还会让你本就复杂的 SQL 语句更加混乱不堪。
  • 因此,如果你需要做一些很复杂的操作,最好用 XML 来映射语句。

通过反射机制实现

本质 : 反射机制

底层 : 动态代理!

在这里插入图片描述

mybatis执行流程

在这里插入图片描述

8.3、 CRUD

  1. 接口

        @Select("select * from user")
        List<User> getUsers();
    
        @Select("select * from user where id = #{uid}")
        User getUserByID(@Param("uid") int id);
    
        @Insert("insert into user(id,name,pwd) values(#{id},#{name},#{password})")
        int addUser(User user);
    
        @Update("update user set name = #{name} where id = #{uid}")
        int updateUser(@Param("uid") int id, @Param("name")String name);
    
        @Delete("delete from user where id = #{id}")
        int deleteUser(int id);
    
  2. 测试

    public void getUsers(){
        SqlSession sqlSession = new MybatisUtils().getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        /*
            List<User> users = mapper.getUsers();
            for (User user : users) {
                System.out.println(user);
            }
            */
        //User userByID = mapper.getUserByID(1);
        //System.out.println(userByID);
        //int hello = mapper.addUser(new User(4, "hello", "123165"));
        //int row = mapper.updateUser(4, "to");
        int row = mapper.deleteUser(5);
        sqlSession.close();
    }
    

关于@Param()

  • 参数为基本类型的时候,都要加上!
  • 参数只有一个基本类型的时候可以忽略,但是建议加上!
  • 引用类型不需要加
  • 我们在sql中引用的属性名就是我们@Param()中设定的属性名

#{} ${} 区别

  • #{} 可以防止sql注入
  • #{} 将传入的数据当成一个字符串
  • ${} 将传入的数据直接显示在sql中

9. Lambok

Project Lombok is a java library that automatically plugs into your editor and build tools, spicing up your java.
Never write another getter or equals method again, with one annotation your class has a fully featured builder, Automate your logging variables, and much more.
  • java library
  • plugs
  • build tools

使用步骤

  1. 在IDEA中下载lambok插件
  2. 引入外部包
  3. 使用注解使用

10. 多对一处理

10.1、 搭建测试环境

  1. 导入lambok

    IDEA2021 已经不支持lambok插件

  2. 新建实体类Teacher Student

  3. 建立Mapper接口

  4. 建立Maooer.xml文件

  5. 在核心配置文件中绑定注册我们的Mapper接口或者文件

  6. 测试查询是否能够成功!

  7. 搭建成功!

在这里插入图片描述

  • 多个学生,对应一个老师
  • 对于学生这边而言, 关联—> 多个学生关联一个老师【多对一】
  • 对于老师这边而言, 集合—> 一个老师有很多学生【一对多】

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, '秦老师');

DROP TABLE `student`
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');

POJO

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

    // 为一个学生绑定一个老师!
    private Teacher teacher;
}


public class Teacher {
    private int id;
    private String name;
}

接口

// 查询所有学生及与他们关联的学生
List<Student> getStudentList();

List<Student> getStudentList2();

Mapper.xml

<!--方式一: 对应sql中的子查询-->
<select id="getStudentList" resultMap="StudentTeacher">
    select * from student;
</select>
<resultMap id="StudentTeacher" 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 teacher where id = #{tid}
</select>


<!--==================================================================================-->

<!--方式二: 对应sql中的联表查询 结果嵌套-->

<select id="getStudentList2" resultMap="StudentTeacher2">
    select s.id sid,s.name sname,t.id tid,t.name tname
    from student s,teacher t
    where s.tid = t.id
</select>

<resultMap id="StudentTeacher2" 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>

测试

public void getStudentList(){
    SqlSession sqlSession = new MybatisUtils().getSqlSession();
    StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
    List<Student> studentList = mapper.getStudentList2();
    for (Student student : studentList) {
        System.out.println(student);
    }
    sqlSession.close();
}

在这里插入图片描述

注意

  • 实体类中重写toString()方法 不然查出来的对象是hashcode

  • 联表查询中别名之后要对应

    <resultMap id="StudentTeacher2" 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>
    

11. 一对多处理

搭建环境

  1. 导入lambok

    IDEA2021 已经不支持lambok插件

  2. 新建实体类Teacher Student

  3. 建立Mapper接口

  4. 建立Maooer.xml文件

  5. 在核心配置文件中绑定注册我们的Mapper接口或者文件

  6. 测试查询是否能够成功!

  7. 搭建成功!

  • 多个学生,对应一个老师
  • 对于学生这边而言, 关联—> 多个学生关联一个老师【多对一】
  • 对于老师这边而言, 集合—> 一个老师有很多学生【一对多】

POJO

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;
}

按照查询嵌套查询

<select id="getTeacherById" resultMap="TeacherStudent">
    select * from teacher where id = #{tid}
</select>

<resultMap id="TeacherStudent" type="Teacher">
    <collection property="students" javaType="ArrayList" ofType="Student"
                select="getStudents" column="id"/>
</resultMap>

<select id="getStudents" resultType="Student">
    select * from student where tid = #{tid}
</select>

按照结果查询

<select id="getTeacherById2" resultMap="TeacherStudent2">
    select t.id tid,t.name tname,s.id sid,s.name sname
    from student s,teacher t
    where s.tid = t.id
</select>

<resultMap id="TeacherStudent2" type="Teacher">
    <result property="id" column="tid"/>
    <result property="name" column="tname"/>
    <collection property="students" ofType="Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <result property="tid" column="tid"/>
    </collection>
</resultMap>
  • 推荐联表查询 即结果嵌套 方便调试!

小结

  1. 关联 - association 【多对一】
  2. 集合 - collection 【一对多】
  3. javaType & ofType
    1. javaType 用来指定实体类中的属性的类型
    2. ofType 用来指定映射到List或者集合中的pojo类型,即泛型中的约束!

注意点

  • 保证SQL的可读性 通俗易懂
  • 注意一对多和多对一中的属性名字段名问题!
  • 如果问题不好排查 建议使用日志 建议使用log4j

慢SQL 加索引 学习思路 尽量不要自己写!

面试高频

  • 引擎
  • InnoDB底层原理
  • 索引
  • 索引优化

12. 动态SQL

12.1、什么是动态SQL

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

摆脱根据不同条件拼接 SQL 语句的痛苦

/*如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。
*/
if
choose (when, otherwise)
trim (where, set)
foreach

12.2、环境搭建

  1. 导包
  2. 配置文件
  3. 工具类
  4. pojo
  5. dao对应的Mapper & xml
  6. 测试环境

12.3、 IF

接口

// 根据需求查询blog
List<Blog> queryBlogIf(Map map);

xml

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

测试

SqlSession sqlSession = new MybatisUtils().getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);

Map<Object, Object> map = new HashMap<>();
//map.put("title","Mybatis如此简单");
map.put("author","狂神说");

List<Blog> blogs = mapper.queryBlogIf(map);
for (Blog blog : blogs) {
    System.out.println(blog);
}

sqlSession.close();

12.4、choose、when、otherwise

choose 只会选择其中一个条件查询 相当于swich

<select id="queryBlogChoose" parameterType="map" resultType="blog">
    select *
    from mybatis.blog
    <where>
        <!--choose 只会选择其中一个条件查询 相当于swich-->
        <choose>
            <when test="title != null">
                title = #{title}
            </when>
            <when test="author != null">
                author = #{author}
            </when>
            <otherwise>
                views = #{views}
            </otherwise>
        </choose>
    </where>
</select>
@Test
public void queryBlogChoose(){
    SqlSession sqlSession = new MybatisUtils().getSqlSession();
    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);

    HashMap<Object, Object> map = new HashMap<>();
    map.put("title","Java如此简单");
    map.put("author","狂神说");
    map.put("views",9999);

    List<Blog> blogs = mapper.queryBlogChoose(map);
    for (Blog blog : blogs) {
        System.out.println(blog);
    }

    sqlSession.close();
}

12.5、 trim、where、set

<where>
    <!--choose 只会选择其中一个条件查询 相当于swich-->
    <choose>
        <when test="title != null">
            title = #{title}
        </when>
        <when test="author != null">
            author = #{author}
        </when>
        <otherwise>
            views = #{views}
        </otherwise>
    </choose>
</where>

<update id="updateBlog" parameterType="map">
    update mybatis.blog
    <set>
        <include refid="if-title-author"/>
    </set>
    where id = #{id};
</update>

<sql id="if-title-author">
    <if test="title != null">
        title = #{title},
    </if>
    <if test="author != null">
        author = #{author}
    </if>
</sql>
public void updateBlog(){
    SqlSession sqlSession = new MybatisUtils().getSqlSession();
    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);

    HashMap<Object, Object> map = new HashMap<>();
    map.put("title","Java如此简单2");
    map.put("author","狂神说2");
    map.put("id","825678625c4f45bab1465beb121c49bf");

    mapper.updateBlog(map);
    sqlSession.close();
}

12.6、 SQL片段

<update id="updateBlog" parameterType="map">
    update mybatis.blog
    <set>
        <include refid="if-title-author"/>
    </set>
    where id = #{id};
</update>

<sql id="if-title-author">
    <if test="title != null">
        title = #{title},
    </if>
    <if test="author != null">
        author = #{author}
    </if>
</sql>

12.7、 foreach

<select id="queryBlogForeach" parameterType="map" resultType="blog">
    select *
    from mybatis.blog
    <where>
        <foreach collection="ids" open="(" separator="or" close=")" item="id">
            id = #{id}
        </foreach>
    </where>
</select>
@Test
public void queryBlogForeach(){
    SqlSession sqlSession = new MybatisUtils().getSqlSession();
    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);

    HashMap<Object, Object> map = new HashMap<>();

    ArrayList<String> ids = new ArrayList<>();
    //ids.add("825678625c4f45bab1465beb121c49bf");

    map.put("ids",ids);

    List<Blog> blogs = mapper.queryBlogForeach(map);
    for (Blog blog : blogs) {
        System.out.println(blog);
    }

    sqlSession.close();
}

12.8、 小结

所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面,去执行逻辑代码

  • if
  • choose (when, otherwise)
  • trim (where, set)
  • foreach

动态SQL其实就是在拼接SQL,我们只要保证SQL的正确性,按照SQL的格式去排列组合就好了

建议:

先去MySQL中写好SQL 做好测试

13. 缓存

13.1、 简介

查询  :  连接数据库 ,耗资源!
	一次查询的结果,给他暂存在一个可以直接取到的地方!--> 内存 : 缓存
	
我们再次查询相同数据的时候,直接走缓存,就不用走数据库了
  1. 什么是缓存【cache】?

    • 存在内存中的临时数据
    • 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题!
  2. 为什么使用缓存?

    • 减少和数据库交互次数,减少系统开销,提高系统效率!
  3. 什么样的数据能使用缓存?

    • 经常使用且不改变的数据。

13.2、 Mybatis缓存

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

13.3、 一级缓存

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

测试步骤:

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

缓存失效的情况:

  1. 查询不同的记录

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

  3. 查询不同的Mapper.xml

  4. 手动清理缓存

    sqlSession.clear();
    

小结:

一级缓存默认是开启的,也不会关闭,值会随着sqlSession的关闭而关闭,只在一次sqlSession中有效,也就是拿到连接到关闭连接这个区间段

一级缓存相当于一个Map

13.4、 二级缓存

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

步骤:

  1. 开启全局缓存

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

    <!--在当前Mapper.xml中使用二级缓存-->
    <cache/>
    

    也可以自定义参数

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

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

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

小结:

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

13.5、 缓存原理

在这里插入图片描述

13.6、 自定义缓存

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>

Redis数据库来做缓存! K-V

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值