Mybatis详解

Mybatis

Mytabis的官方文档的地址:https://mybatis.org/mybatis-3/zh/configuration.html

环境:

  • JDK1.8
  • mysql5.7
  • maven3.6.1
  • IDEA

回顾:

  • JDBC
  • mysql
  • java基础
  • maven 创建maven项目
  • junit 单元测四

框架的配置文件

建议:最好的方式去官网查询

1、Mybatis的简介

1.1、Mybatis的简介

  1. mybatis是一款优秀的持久层框架
  2. 它支持制定化SQL,存储过程及高级映射
  3. Mybatis避免了几乎所有的JDBC代码和手动设置参数及获取结果集
  4. Mybatis可以使用简单的XML或注解来配置和映射原生类型,接口和java的POJO为数据库的记录
  5. 2013年迁移到GitHub

如何获得Mybatis

1.2、持久化

数据的持久化,

  • 持久化就是将程序的数据在持久状态和瞬时状态的转化过程
  • 内存的特性:断电即失
  • 例子: 数据库(JDBC)io文件持久化

为什么需要持久化

  • 保证重要数据的不会丢失,
  • 内存的成本太高

1.3、持久层

定义:完成持久化工作的代码块

1.4、Mybatis的优点

  • 方便
  • 传统的JDBC的代码太复杂,能够很好的降低代码的复杂度
  • 帮助程序员将数据存入数据库中。
  • 优点
    • 简单易学
    • 灵活
    • sql和代码分离,提高了可维护性
    • 提供映射标签,支持对象与数据库的orm字段的关系映射
    • 提供对象关系映射标签,支持对象关系组件维护
    • 提供xml标签,支持编写动态SQL

2、第一个Mybatis程序

搭建环境–>导入Mybatis–>编写代码–>进行测试

搭建一个数据库

INSERT into `user` (`id`,`name`,`pwd`) VALUES 
(1,'张三','123456'),
(2,'李四','123456'),
(3,'王五','123456'),
(4,'赵六','123456')

新建maven项目

<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>8.0.11</version>
</dependency>
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.5.2</version>
</dependency>
<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.12</version>
</dependency>

image-20211027123727759

编写工具类

package com.li.util;

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;

public class sqlsessionDemo {

    public SqlSessionFactory test() throws IOException {
        //进行文件读取
        String resource = "mybatis-config.xml";
        //将文件进行数据流的转化
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //通过SqlSessionFactoryBuilder构造SqlSessionFactory工厂
          SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
         return sqlSessionFactory;
    }

}

编写实体类

package com.li.Pojo;

public class user {
    private int id;
    private String name;
    private String pwd;

    public user(int id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }

    public user() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }


    @Override
    public String toString() {
        return "user{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                '}';
    }
}

进行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">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
<!--                进行数据库的连接-->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=GMT%2B8&amp;useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value=""/>
            </dataSource>
        </environment>
    </environments>
<!--    设置mybatis读取的数据搜索层的类-->
    <mappers>
        <mapper resource="com/li/Dao/UserMapper.xml"/>
    </mappers>
</configuration>

Dao层的编写

package com.li.Dao;

import com.li.Pojo.user;

import java.util.List;

public interface UserMapper {
   public List<user> selectUser() ;

}


接口的实现类

<?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">
<mapper namespace="com.li.Dao.UserMapper">
   <select id="selectUser" resultType="com.li.Pojo.user">
       select * from user;
   </select>
</mapper>

进行测试

package com.li.test;

import com.li.Dao.UserMapper;
import com.li.Pojo.user;
import com.li.util.sqlsessionDemo;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.io.IOException;
import java.util.List;

public class selectUserTest {
    public static void main(String[] args) throws IOException {
   sqlsessionDemo ss=    new sqlsessionDemo();
    SqlSessionFactory sqlSessionFactory=ss.test();
//    获取sqlSession
       SqlSession sqlSession = sqlSessionFactory.openSession();
//       获取UserMapper
       UserMapper userMapper= sqlSession.getMapper(UserMapper.class);
//       调用UserMapper中的方法
     List<user> users= userMapper.selectUser();
//     进行数据的展示
        System.out.println(users.toString());


    }

}

注,在maven中,扫描xml文件,maven默认的为resources中的文件,当xml文件放在了java文件夹下,需要在maven中添加相应的依赖进行扫描

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

image-20211027161706396

3、mybatis中的增删改查

3.1、namespace

注: namespace中的文件名需要与dao层的文件名一致

<mapper namespace="com.li.Dao.UserMapper">

3.2、select

选择,查询语句

 <select id="selectUser" resultType="com.li.Pojo.user">
  • id;表示对应的namespace对应类中的方法名
  • resultType:sql语句执行完成之后的返回值类型
  • parameterType:传递的参数类型

3.3、update

//进行数据的更改
   public  int updateUser(HashMap hashMap);
<!--    进行数据的修改-->
    <update id="updateUser" parameterType="HashMap">
        update user set name=#{name},pwd=#{pwd} where  id=#{id}
    </update>
@Test
    public void updateUser() throws IOException {
        sqlsessionDemo sqlsessionDemo = new sqlsessionDemo();
        SqlSessionFactory test = sqlsessionDemo.test();
        SqlSession sqlSession = test.openSession();
        HashMap hashMap=new HashMap();
        hashMap.put("id",1);
        hashMap.put("name","哈哈");
        hashMap.put("pwd","1234567");
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        String i = String.valueOf(mapper.updateUser(hashMap));
        if (i!=null && i!=""){
            System.out.println("修改成功");
        }
        sqlSession.commit();//进行数据的提交
        sqlSession.close();

在进行数据修改的时候需要开启事务,不然数据修改无效

3.4、insert

 //进行数据的插入
int insertUser(HashMap hashMap);
  //进行数据的写入 
<insert id="insertUser" parameterType="HashMap">
        insert  into user (id,`name`,pwd) values (#{id},#{name},#{pwd})
    </insert>
//    进行数据的插入
    @Test
    public void insertUser() throws IOException {
        sqlsessionDemo sqlsessionDemo = new sqlsessionDemo();
        HashMap hashMap=new HashMap();
        SqlSessionFactory test = sqlsessionDemo.test();
        SqlSession sqlSession = test.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        hashMap.put("id",5);
        hashMap.put("name","呵呵");
        hashMap.put("pwd","12345678");
        String i = String.valueOf(mapper.insertUser(hashMap));
        if(i!=null){
            System.out.println("数据的写入成功");

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


    }

在进行数据修改的时候需要开启事务,不然数据修改无效

3.5、delete

//   进行数据的删除
   int deleteUser(int id);
<!--    进行数据的删除-->
    <delete id="deleteUser" parameterType="int">
        delete from user where  id=#{id}
    </delete>

  @Test
    public void deleteUser() throws IOException {
        sqlsessionDemo sqlsessionDemo = new sqlsessionDemo();
        SqlSessionFactory test = sqlsessionDemo.test();
        SqlSession sqlSession = test.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        String i = String.valueOf(mapper.deleteUser(2));
        if (i!=null){
            System.out.println("数据删除成功");
        }
        sqlSession.commit();
        sqlSession.close();
    }

在进行数据修改的时候需要开启事务,不然数据修改无效

6、注意事项

<mappers>
    resource中的路径必须是/不能是点
        <mapper resource="com/li/Dao/UserMapper.xml"/>
</mappers>
  • 程序的配置文件必须符合规定

7、模糊查询

  1. java代码执行时候,传递通配符%%

    List<User> userList=mapper.getUserList("%李%")
    
  2. 在sql拼接中使用字符串

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

4、配置的解析

4.1、核心配置文件

image-20211028100945910

  • mybatis-config.xml
  • Mybatis的配置文件包含了会深深影响Mybatis的行为的设置和熟属性信息
configuration(配置)
properties(属性)
setting(设置)
typeAliases(类型别名)
typeHandler(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManger(是五处理器)
dataSource(数据源)
databaseIdprovider(数据库产商标识)
mapper(映射器)

image-20211103152513690

2、环境配置

Mybatis可以配置适应多种环境

注:尽管可以配置多种环境,但是每个SqlSessionfactory实例只能选择一种环境

Mybatis默认的事务管理器是JDBC 连接池是POOLED

image-20211028121500554

3、属性(properties)

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-enSB7IVX-1635924824384)(…/AppData/Roaming/Typora/typora-user-images/image-20211028121538157.png)]

注:在xml的配置文件之中,每一个属性都有其固有的顺序.

创建db.properties文件

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
username=root
password=lyj18366635303

进行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>
    <properties resource="db.properties">

    </properties>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
<!--                进行数据库的连接-->
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
<!--    设置mybatis读取的数据搜索层的类-->
    <mappers>
        <mapper resource="com/li/Dao/UserMapper.xml"/>
    </mappers>
</configuration>

image-20211028122352401

注:properties中也可以进行值的设置,但是其优先级小于外部文件

  • 可以直接引入外部文件
  • 可以在其中添加一些属性配置
  • 如果两个文件有同一个字段,优先使用外部的配置文件

4、别名typeAliases

类型别名是为Java类型设置一个短的名字,它之和XML配置有关,存在意义仅在于减少类完全限定名的冗余。

例子:

<typeAliases>
  <typeAlias alias="Author" type="domain.blog.Author"/>
  <typeAlias alias="Blog" type="domain.blog.Blog"/>
  <typeAlias alias="Comment" type="domain.blog.Comment"/>
  <typeAlias alias="Post" type="domain.blog.Post"/>
  <typeAlias alias="Section" type="domain.blog.Section"/>
  <typeAlias alias="Tag" type="domain.blog.Tag"/>
</typeAliases>

也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean,比如:

<typeAliases>
  <package name="domain.blog"/>
</typeAliases>

每一个在包 domain.blog 中的 Java Bean,在没有注解的情况下,会使用 Bean 的首字母小写的非限定类名来作为它的别名。 比如 domain.blog.Author 的别名为 author;若有注解,则别名为其注解值。见下面的例子:

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

5、设置(setting)

这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为。 下表描述了设置中各项设置的含义、默认值等。

<settings>
  <setting name="cacheEnabled" value="true"/>
  <setting name="lazyLoadingEnabled" value="true"/>
  <setting name="multipleResultSetsEnabled" value="true"/>
  <setting name="useColumnLabel" value="true"/>
  <setting name="useGeneratedKeys" value="false"/>
  <setting name="autoMappingBehavior" value="PARTIAL"/>
  <setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>
  <setting name="defaultExecutorType" value="SIMPLE"/>
  <setting name="defaultStatementTimeout" value="25"/>
  <setting name="defaultFetchSize" value="100"/>
  <setting name="safeRowBoundsEnabled" value="false"/>
  <setting name="mapUnderscoreToCamelCase" value="false"/>
  <setting name="localCacheScope" value="SESSION"/>
  <setting name="jdbcTypeForNull" value="OTHER"/>
  <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
</settings>

6、可能会用的插件(plugins)

  • mybatis-generator-core
  • mybatis-plus(更加的简化mybatis)
  • 通用mapper

7、映射器(mappers)

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

使用相对于类路径的资源引用

<mappers>
  <mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
  <mapper resource="org/mybatis/builder/BlogMapper.xml"/>
  <mapper resource="org/mybatis/builder/PostMapper.xml"/>
</mappers>

使用映射器接口实现类的完全限定类名

<mappers>
  <mapper class="org.mybatis.builder.AuthorMapper"/>
  <mapper class="org.mybatis.builder.BlogMapper"/>
  <mapper class="org.mybatis.builder.PostMapper"/>
</mappers>

注意点

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

使用扫描包进行注入绑定

<mappers>
  <package name="org.mybatis.builder"/>
</mappers>

注意点

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

8、生命周期

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

image-20211028142644679

SqlsessionFactoryBuilder:

  • 一旦创建SqlSessionFactory,就不再需要
  • 作用域为局部变量

SqlsessionFactory

  • 类似于数据库的连接池
  • 作用域为全局变量
  • 最简单的是使用单例模式后者是静态单例模式

SqlSession类似于

  • 连接到连接池的请求
  • 其需要开启和关闭
  • 最佳的作用域在一个方法之中,在用完之后需要进行关闭
  • 否则资源会被占用!
  • image-20211028143328423

其中的每个Mapper代表的一个数据库的业务及接口方法

5、结果集映射(ResultMap)解决属性名与字段名不一致的问题

注:当实体类中的字段名与数据库中的字段名不一致时会导致所查询的字段搜索不到

image-20211028212850615

image-20211028212950047

解决方法

方法一

image-20211028213258541

image-20211028213226743

方法二

<resultMap id="userResultMap" type="com.li.Pojo.user">
        <result property="password" column="pwd"/>
</resultMap>
<select id="selectUser" resultMap="userResultMap">
       select * from user;
</select>

image-20211028214533101

image-20211028214551302

6、日志

6.1、日志工厂

作用:用来对数据库进行排错

image-20211028215018182

  • SLF4J
  • LOG4J(掌握i)
  • LOG4J2
  • JDK_LOGGING
  • COMMONS_LOGGING
  • STDOUT_LOGGING(需要掌握)
  • NO_LOGGING

在Mybatis中具体使用哪个日志,在设置中设定、不存在默认值

**STDOUT_LOGGING(需要掌握)**标准日志输出,在setting中设置

6.2、Log4j

定义

  • Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件,甚至是套接口服务器、NT的事件记录器、UNIX Syslog守护进程等;我们也可以控制每一条日志的输出格式;通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。最令人感兴趣的就是,这些可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
  1. 先导入log4j的包(其所需要的maven依赖)

     <dependency>
               <groupId>log4j</groupId>
               <artifactId>log4j</artifactId>
               <version>1.2.17</version>
     </dependency>
          
    
  2. log4j.properties

    # priority  :debug<info<warn<error
    #you cannot specify every priority with different file for log4j
    log4j.rootLogger=debug,stdout,info,debug,warn,error 
    
    #console
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender 
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 
    log4j.appender.stdout.layout.ConversionPattern= [%d{yyyy-MM-dd HH:mm:ss a}]:%p %l%m%n
    #info log
    log4j.logger.info=info
    log4j.appender.info=org.apache.log4j.DailyRollingFileAppender 
    log4j.appender.info.DatePattern='_'yyyy-MM-dd'.log'
    log4j.appender.info.File=./src/com/li/log/info.log
    log4j.appender.info.Append=true
    log4j.appender.info.Threshold=INFO
    log4j.appender.info.layout=org.apache.log4j.PatternLayout 
    log4j.appender.info.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss a} [Thread: %t][ Class:%c >> Method: %l ]%n%p:%m%n
    #debug log
    log4j.logger.debug=debug
    log4j.appender.debug=org.apache.log4j.DailyRollingFileAppender 
    log4j.appender.debug.DatePattern='_'yyyy-MM-dd'.log'
    log4j.appender.debug.File=./src/com/hp/log/debug.log
    log4j.appender.debug.Append=true
    log4j.appender.debug.Threshold=DEBUG
    log4j.appender.debug.layout=org.apache.log4j.PatternLayout 
    log4j.appender.debug.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss a} [Thread: %t][ Class:%c >> Method: %l ]%n%p:%m%n
    #warn log
    log4j.logger.warn=warn
    log4j.appender.warn=org.apache.log4j.DailyRollingFileAppender 
    log4j.appender.warn.DatePattern='_'yyyy-MM-dd'.log'
    log4j.appender.warn.File=./src/com/hp/log/warn.log
    log4j.appender.warn.Append=true
    log4j.appender.warn.Threshold=WARN
    log4j.appender.warn.layout=org.apache.log4j.PatternLayout 
    log4j.appender.warn.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss a} [Thread: %t][ Class:%c >> Method: %l ]%n%p:%m%n
    #error
    log4j.logger.error=error
    log4j.appender.error = org.apache.log4j.DailyRollingFileAppender
    log4j.appender.error.DatePattern='_'yyyy-MM-dd'.log'
    log4j.appender.error.File = ./src/com/hp/log/error.log 
    log4j.appender.error.Append = true
    log4j.appender.error.Threshold = ERROR 
    log4j.appender.error.layout = org.apache.log4j.PatternLayout
    log4j.appender.error.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss a} [Thread: %t][ Class:%c >> Method: %l ]%n%p:%m%n
    
  3. 配置log4j为日志的实现

     <settings>
            <setting name="logImpl" value="LOG4J"/>
        </settings>
    
  4. 直接测试运行

简单使用

//log4j的实现类   注:需要导入放入包为apache下的log4j的包  
private static Logger logger = Logger.getLogger(selectUserTest.class);
//selectUserTest为当前类

测试

logger.debug("debug: hello~");
        logger.info("info: hello~");
        logger.warn("warn: hello~");
        logger.error("error: hello~");

7、分页

分页的原因

  • 减少数据的处理量

limit分页()建议使用

select * from 表明 limit 起始位置,页面的大小;
select * from 表明 limit 02; --煤业显示两个从弟0哥开始


RowBounds分页

分页插件 mybatis PageHelper

8、使用注解开发

8.1、面向接口编程

注:面向接口编程的原因石解耦,实现接口与功能实现的分离

接口的分类

  1. 第一个类是对一个个体的抽象,它对应为一个抽象体
  2. 第二类是对一个个体某一方面的抽象,形成一个抽象面

一个个体可能有多个抽象面,抽象体与抽象面数有区别的

三个面的区别

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

8.2、使用注解开发

例子:

package org.mybatis.example;
public interface BlogMapper {
  @Select("SELECT * FROM blog WHERE id = #{id}")
  Blog selectBlog(int id);
}

image-20211030151755562

关于@param()注解

  • 基本类型的参数或者是String类型需要加上
  • 引用类型不需要加
  • 如果只有一个基本类型的话,可以忽略,但是建议都加上
  • 我们在SQL中引用的就是我们@param中设定的属性

#{}与${}的区别

  • 一般都是使用#{},可以有效的防止sql注入

9、Lombok

简介:Lombok 是一种 Java 实用工具,可用来帮助开发人员消除 Java 的冗长,尤其是对于简单的 Java 对象(POJO)。它通过注释实现这一目的。通过在开发环境中实现 Lombok,开发人员可以节省构建诸如 hashCode() 和 equals() 这样的方法以及以往用来分类各种 accessor 和 mutator 的大量时间。

使用步骤:

  1. 在IDEA中安装Lombok插件

    image-20211030191441088

    image-20211030191622953

  2. 在项目中导入Lombok的jar包或者是maven依赖

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.16.18</version>
    </dependency>
    
  3. 使用时在实体类上加上注解便可以

    image-20211030191916457

10、多对一处理

多对一:

实体类

package com.li.Pojo;

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

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public Teacher getTeacher() {
        return teacher;
    }

    public void setTeacher(Teacher teacher) {
        this.teacher = teacher;
    }

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

package com.li.Pojo;

public class Teacher {
    private int tid;
    private  String name;

    public int getTid() {
        return tid;
    }

    public void setTid(int tid) {
        this.tid = tid;
    }

    public String getName() {
        return name;
    }

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

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

按照查询进行嵌套处理

   <select id="getStudentInformation2" resultMap="getStudentInformation2">
        select * from student
    </select>
    <select id="selectTeacher" resultType="com.li.Pojo.Teacher">
        select teacher.name  from teacher where tid=#{id}
    </select>
    <resultMap id="getStudentInformation2" type="com.li.Pojo.Student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <association property="teacher" column="tid" javaType="com.li.Pojo.Teacher" select="selectTeacher"/>
    </resultMap>

注:当实体类中存在负责的属性的时候,我们要进行单独的处理:当属性为对象的时候采用:association,集合采用collection

按照结果进行嵌套处理

 <select id="getStudentInformatin" resultMap="getStudentInformation">
        select s.id as sid,s.`name` as sname,t.`name` as tname FROM student as s,teacher AS t WHERE s.tid=t.tid
    </select>
    <resultMap id="getStudentInformation" type="com.li.Pojo.Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
       <association property="teacher" javaType="com.li.Pojo.Teacher">
           <result property="name" column="tname"/>
       </association>
    </resultMap>

11、一对多

按照结果进行嵌套处理

<select id="getTeacherInformation" resultMap="getTeacherInformation1">
        select t.tid as ttid,t.`name` as tname,s.`name` as sname FROM teacher as t,student as s WHERE t.tid=s.tid and  t.tid=#{tid}
    </select>
    <resultMap id="getTeacherInformation1" type="com.li.Pojo.Teacher1">
        <result property="tid" column="ttid"/>
        <result property="name" column="tname"/>
        <!--
            当实体类中存在负责的属性的时候,我们要进行单独的处理:当属性为对象的时候采用:association,集合采用collection
            处理对象获取其对象类型的时候采用javaType
            在处理集合的获取其类型的时候采用的是ofType
        -->
        <collection property="student1s" ofType="com.li.Pojo.Student1" >
            <result property="name" column="sname"/>
        </collection>
    </resultMap>

按照查询进行嵌套处理

--    =======================================================================================-->
    <select id="getTeacher1Information" resultMap="getTeacherInformation2">
        select * from teacher where tid=#{tid}
    </select>

    <select id="getStudent" resultType="com.li.Pojo.Student1">
        select * from student where tid=#{tid}
    </select>

    <resultMap id="getTeacherInformation2" type="com.li.Pojo.Teacher1">
        <collection property="student1s" column="tid" javaType="ArrayList" ofType="com.li.Pojo.Student1" select="getStudent"/>
    </resultMap>

小结

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

注意点

  • 保证SQL的可读性
  • 注意一对多和多对一中属性名和字段名的问题
  • 如果问题不好排查错误,可以使用日志,建议使用log4j

面试中的高频问题

  • Mysql的引擎问题
  • innoDB底层原理
  • 索引
  • 索引优化

12、动态SQL

定义:根据不同的条件生成不同的sql语句

12.1、IF

<select id="getTeacher1Information" resultMap="getTeacherInformation2">
    select * from teacher where 1=1
    <if test="tid!=null and tid!=''">and tid=#{tid} </if>
 </select>

12.2、choose、when、otherwise

MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。只能成立一个条件

<select id="getUserInformation" resultType="com.li.Pojo.user" parameterType="HashMap">
        select * from user where 1=1
        <choose>
            <when test="id!= null ">
                AND id = #{id}
            </when>
            <when test="name !=null and name!=''">and `name`=#{name}</when>
            <otherwise>
                and pwd="12345678"
            </otherwise>
        </choose>
    </select>

注;在choose中只能满足一个条件,类似与case

12.3、trim(where,set)

 <update id="updateUserInformation" parameterType="HashMap">
        update user
       <set>
            <if test="name!=null "> `name` =#{name},</if>
            <if test="pwd!=null "> pwd =#{pwd}</if>
       </set>
        where  id=#{id}
</update>

注:自定义 trim 元素来定制 where 元素的功能

SQL片段

有时候我们会将一些公共的SQL语句抽取出来方便复用

foreach

<select id="selectPostIn" resultType="domain.blog.Post">
  SELECT *
  FROM POST P
  WHERE ID in
  <foreach item="item" index="index" collection="list"
      open="(" separator="," close=")">
        #{item}
  </foreach>
</select>

例子:

<select id="getInformation" parameterType="HashMap" resultType="com.li.Pojo.user">
        select  * from user
        <where>
            <foreach collection="ids" item="id" open="and (" separator="or" close=")" >
                id=#{id}
            </foreach>
        </where>
    </select>

image-20211031211910631

13、缓存

13.1、简介

定义:

  • 存在内存中的临时数据
  • 将用户经常查询的数据放在缓存之中,用户去查询数据不需要在磁盘中进行查询,直接存缓存中查询,从而提高查询的效率,解决了高并发系统的问题。

为什么使用缓存

  • 减少和数据库的交互次数,减少系统的开销,提高系统的效率

什么样的数据可以使用缓存

  • 经常查询并且不经常改变的数据

13.2、Mybatis缓存

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

13.3、一级缓存

  • 一级缓存也叫本地缓存
    • 与数据库同一次会话期间查询到的数据会放到本地缓存中
    • 以后如果获取相同的数据,直接在缓存中拿,没必要再去查询数据库;
  • 缓存失效的原因
    • 查询不同的结果
    • 怎删改查,可能会改变原来的数据
    • 查询不同的Mapper.xml
    • 手动的清出缓存

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

13.4、二级缓存

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

小结:

  • 只要开启了二级缓存,在同一个Mapper中便有效
  • 所有的数据都会放在一级缓存中
  • 只有当会话提交,或者是关闭之后,才会提交到二级缓存中

13.5、缓存的原理

image-20211103142031829

13.6、自定义缓存-ehcache

需要的maven配置

<dependency>
  <groupId>org.mybatis.caches</groupId>
  <artifactId>mybatis-ehcache</artifactId>
  <version>1.2.1</version>
</dependency>

eccache的配置问价

<?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="java.io.tmpdir/Tmp_EhCache"/>
    <!--
       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,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
   -->
    <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"/>
  
</ehcache>

在Mapper文件中配置

image-20211103153304111

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,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
–>

<cache
        name="cloud_user"
        eternal="false"
        maxElementsInMemory="5000"
        overflowToDisk="false"
        diskPersistent="false"
        timeToIdleSeconds="1800"
        timeToLiveSeconds="1800"
        memoryStoreEvictionPolicy="LRU"/>
```

在Mapper文件中配置

[外链图片转存中…(img-XFXJN8Av-1635924824400)]

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值