MyBatis基础

MyBatis

官网:https://mybatis.org/mybatis-3/zh/index.html

1. 简介

1.1 什么是Mybatis

  • MyBatis 是一款优秀的持久层框架
  • 它支持自定义 SQL、存储过程以及高级映射。
  • MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。
  • MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

如何获得Mybatis

  • maven仓库

    • <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
      <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis</artifactId>
          <version>3.5.7</version>
      </dependency>
      
      
  • GitHub

    • https://github.com/mybatis/mybatis-3/releases

1.2 持久层

数据持久化

  • 持久化就是将程序得数据在持久状态和瞬时状转化得过程
  • 内存:断电即失
  • 数据库(jdbc),io文件持久化

1.3 持久层

  • 完成持久化工作得代码块
  • 层界限十分明显

1.4 为什么需要Mybatis

  • 帮助程序员将数据库存入到数据库中
  • 方便
  • 简化,框架,自动化
  • 优点:简单易学。灵活。sql和代码分离,提高可维护性。提高xml标签,支持动态编写sql

2. 第一个Mybatis程序

2.1 搭建环境

  • 搭建数据库

  • 新建项目

    1. 新建一个普通得maven项目

    2. 删除src文件

    3. 导入maven依赖

      <!--导入依赖-->
      <!--    mybatis  mysql驱动   junit-->
      <dependencies>
          <!-- mysql驱动 -->
          <dependency>
              <groupId>mysql</groupId>
              <artifactId>mysql-connector-java</artifactId>
              <version>8.0.23</version>
          </dependency>
          <!-- junit -->
          <dependency>
              <groupId>junit</groupId>
              <artifactId>junit</artifactId>
              <version>4.13.2</version>
          </dependency>
          <!-- mybatis -->
          <dependency>
              <groupId>org.mybatis</groupId>
              <artifactId>mybatis</artifactId>
              <version>3.5.7</version>
          </dependency>
      </dependencies>
      

2.2 创建一个模块

  1. 编写mybatis得核心配置文件、

    mybatis-config.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <!-- configuration核心配置文件-->
    <configuration>
        <environments default="development">
            <environment id="development">
                <!--                  JDBC配置-->
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                    <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;userUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=Aisa/Shanghai"/>
                    <property name="username" value="root"/>
                    <property name="password" value="123456"/>
                </dataSource>
            </environment>
        </environments>
        <mappers>
            <mapper resource="org/mybatis/example/BlogMapper.xml"/>
        </mappers>
    </configuration>
    
  2. 编写mybatis得工具类

    package com.mybatis.dao.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;
    
    public class MybatisUtil {
    private static SqlSessionFactory sqlSessionFactory;
    
    static {
    try {
    //        填写配置文件的名称路径
    String resource = "mybatis-config.xml";
    //            读取xml文件
    InputStream inputStream = Resources.getResourceAsStream(resource);
    //            通过工厂模式获得sqlSessionFactory对象
    sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    
    //    既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
    //    SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
    //    你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。
    public static SqlSession getSqlSession() {
    return sqlSessionFactory.openSession();
    }
    }
    
    

2.3 编写代码

  • 实现类

    package com.mybatis.dao.pojo;
    
    public class User {
        private Integer id;
        private String name;
        private String pwd;
    
        public User(Integer id, String name, String pwd) {
            this.id = id;
            this.name = name;
            this.pwd = pwd;
        }
    
        public User() {
        }
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getPwd() {
            return pwd;
        }
    
        public void setPwd(String pwd) {
            this.pwd = pwd;
        }
    }
    
    
  • Dao接口类

    package com.mybatis.dao;
    
    import com.mybatis.pojo.User;
    
    import java.util.List;
    
    public interface UserDao {
        List<User> getUserList();
    }
    
    
  • 接口实现类 由 原来的接口实现类转化为现在的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/Mappr接口-->
    <mapper namespace="com.mybatis.dao.UserDao">
        <!--    查询 id对应接口的方法名字  resultType返回类型-->
        <select id="getUserList" resultType="com.mybatis.pojo.User">
            select * from mybatis.user
        </select>
    </mapper>
    

2.4 测试

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

这个错误就是没有在核心配置文件里面注册

注意:每一个Mapper配置文件都需要在核心配置文件里面注册

<mappers>
    <!--          Mappr文件路径-->
    <mapper resource="com/mybatis/dao/UserMappr.xml"/>
</mappers>
  1. columnNumber: 19; 1 字节的 UTF-8 序列的字节 1 无效。

解决:1.还是建议XML不要有中文注释,2. 把核心配置文件里面的编码改为GBK(要和IDEA的编码一样),3. 把Maven的Pom.xml中的true改为false

  1. Caused by: java.io.IOException: Could not find resource com/mybatis/dao/UserMappr.xml

找不到xml文件,这是Maven资源过滤问题,需要在pom.xml里面手动配置资源过滤

解决:

<!--在build中配置resources,来防止我们资源导出失败的问题-->
<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>
  • junit测试

    package com.mybatis.dao;
    
    import com.mybatis.pojo.User;
    import com.mybatis.utils.MybatisUtil;
    import org.apache.ibatis.session.SqlSession;
    import org.junit.Test;
    
    import java.util.List;
    
    public class UserDaoTest {
        @Test
        public void test() {
            //        获取sqlSession对象
            SqlSession sqlSession = MybatisUtil.getSqlSession();
            //        执行SQL  第一种方法:
            //        使用getMapper方法获取 实现接口
            UserDao mapper = sqlSession.getMapper(UserDao.class);
            List<User> userList = mapper.getUserList();
    
            for (User a : userList) {
                System.out.println(a);
            }
            //    关闭,释放资源
            sqlSession.close();
        }
    }
    
    
    //      了解即可,根据返回值来选择对应的方法  方式二:
    List<User> userList = sqlSession.selectList("com.mybatis.dao.UserDao.getUserList");
    
  • 在test包里面进行

  • 生命周期

    image-20210618140937343

3. CRUD

记得提交事务,MyBatis需要手动提交

3.1 namespace

namespace 包名要和接口名称一致

3.2 CRUD-查Reader

  1. id:就是对应的namespace中的方法名

  2. resultType:SQL语句执行的返回值

  3. parameterType:参数类型

    <select id="getUserById" resultType="com.mybatis.pojo.User" parameterType="Integer">
        # 接口传入地参数类型是什么,parameterType就写什么
        # 接口传入的参数名称是什么,{}里面就写什么
        select * from mybatis.user where id = #{id}
    </select>
    

3.3 CRUD-增:Create

  • 增删改需要提交事务
@Test
public void setUserList() {
   SqlSession sqlSession = MybatisUtil.getSqlSession();

   UserMapper mapper = sqlSession.getMapper(UserMapper.class);
   int userById = mapper.setUserByList(new User(5,"李氏","654"));
   System.out.println(userById);
   //        提交事务
   sqlSession.commit();
   sqlSession.close();
}
<!--对象里面的属性可以直接去出来用-->
<insert id="setUserByList" parameterType="com.mybatis.pojo.User">
    insert into mybatis.user(id, name, pwd) VALUES (#{id},#{name},#{pwd})
</insert>
接口方法:   int setUserByList(User user);

3.4 CRUD-改:Update

@Test
public void updateUserList() {
    SqlSession sqlSession = MybatisUtil.getSqlSession();

    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    int userById = mapper.updateUserByList(new User(5,"函数","23315"));
    System.out.println(userById);
    //        提交事务
    sqlSession.commit();
    sqlSession.close();
}
//    修改
int updateUserByList(User user);
<update id="updateUserByList" parameterType="com.mybatis.pojo.User">
    update mybatis.user
    set name=#{name},
    pwd=#{pwd}
    where id = #{id};
</update>

3.5 CRUD-删:Delete

<delete id="deleteUserByList" parameterType="Integer">
    delete
    from mybatis.user
    where id = #{id};
</delete>
//       删除
int deleteUserByList(Integer id);
@Test
public void deleteUserList() {
    SqlSession sqlSession = MybatisUtil.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    int userById = mapper.deleteUserByList(1);
    System.out.println(userById);
    //        提交事务
    sqlSession.commit();
    sqlSession.close();
}

4. 一些错误

  1. 看报错日志从后面开始看

5. Map和模糊查询

5.1 Map

如果数据库字段或参数过多,可以考虑

int set2UserByList(Map<String,Object> map);
<!--    传递用map的KEY-->
<insert id="set2UserByList" parameterType="map">
    insert into mybatis.user(id, name, pwd)
    VALUES (#{a}, #{b}, #{c})
</insert>
@Test
public void set2UserList() {
    SqlSession sqlSession = MybatisUtil.getSqlSession();

    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    HashMap<String,Object> map = new HashMap<>();
    map.put("a", 1);
    map.put("b", "sdasda");
    map.put("c", "2112");
    int userById = mapper.set2UserByList(map);
    System.out.println(userById);
    //        提交事务
    sqlSession.commit();
    sqlSession.close();
}

Map传递参数,直接在sql中取出key即可

对象传递参数,直接在sql中去对象的属性即可

多个参数用Map或注解

5.2 模糊查询

  1. java代码传递的时候添加通配符 %%

    List<User> get2UserList(String value);
    
    @Test
    public void test1() {
        SqlSession sqlSession = MybatisUtil.getSqlSession();
    
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.get2UserList("%李%");
    
        for (User a : userList) {
            System.out.println(a);
        }
        //    关闭,释放资源
        sqlSession.close();
    }
    
    <select id="get2UserList" resultType="com.mybatis.pojo.User">
        select *
        from mybatis.user where name like #{value}
    </select>
    
  2. 在sql语句中写通配符

    <select id="get2UserList" resultType="com.mybatis.pojo.User">
        select *
        from mybatis.user where name like "%"#{value}"%";
    </select>
    

6 . 配置解析

6.1 核心配置文件

  • mybatis-config.xml

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

6.2 环境配置(environments)

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

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

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

6.3 属性(properties)

这些属性可以在外部进行配置,并可以进行动态替换。

编写一个配置文件 db.properties

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;userUnicode=true&amp;characterEncoding=UTF-8
username=root
password=123456

在核心配置文件中引入

<properties resource="db.properties">
</properties>

使用

<!--    引入外部配置-->
<properties resource="db.properties">
</properties>
<environments default="development">
    <environment id="development">
        <!--                  JDBC配置   使用外部配置-->
        <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>
  • 可以直接使用外部文件
  • 可以在引入时使用一些属性配置
  • 如果什么两个同时存在,外部文件优先级高

这是核心配置文件写属性的顺序

image-20210618194852525

6.4 类型别名(typeAliases)

  • 类型别名可为 Java 类型设置一个缩写名字。 -
  • 它仅用于 XML 配置,意在降低冗余的全限定类名书写。
  1. typeAlias:
<!--    起别名-->
<typeAliases>
    <typeAlias type="com.mybatis.pojo.User" alias="User"/>
</typeAliases>
  1. package:也可以指定一个包名,MyBatis 会在包名下面搜索需要的类,在没有注解的情况下,会使用 类名的首字母小写的非限定类名来作为它的别名。
<!--    起别名-->
<typeAliases>
    <package name="com.mybatis.pojo"/>
</typeAliases>

第一种可以自定义别名

第二种不能,但是可以通过注解来起别名@Alias("ni")

6.5 设置(settings)

image-20210618201457936

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-D9k9t5Wn-1632751506113)(image-20210618201514692.png)]

6.6 其它

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

6.7 映射器(mappers)

注册绑定

方式一:

<mappers>
    <!--          Mapper文件路径-->
    <mapper resource="com/mybatis/Mapper/UserMapper.xml"/>
</mappers>

方式二:使用class文件绑定

<mappers>
    <mapper class="com.mybatis.Mapper.UserMapper"/>
</mappers>

注意点:

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

方式三:使用扫描包

<mappers>
    <package   name="com.mybatis.Mapper"/>
</mappers>

注意点:

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

6.8 生命周期和作用域

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

  • SqlSessionFactoryBuilder

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

    • SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例
    • SqlSessionFactory 的最佳作用域是应用作用域,程序开始就开始,结束就结束
    • 最简单的就是使用单例模式或者静态单例模式
  • SqlSession

    • 连接到连接池的一个请求
    • 关闭
    • 它的最佳的作用域是请求或方法作用域
    • 因为这个不是线程安全的,所有用完要马上关闭,否则会造成资源占用

7. ResultMap结果集映射

7.1 解决属性名和字段名不一致问题

image-20210618213530242

image-20210618213754008

解决方法:

  • 起别名

    <select id="getUserList" resultType="com.mybatis.pojo.User">
        select pwd as password,name,id
        from mybatis.user
    </select>
    

    image-20210618213909160

7.2 ResultMap

image-20210618221047813

  • ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。

  • ResultMap 的优秀之处——你完全可以不用显式地配置它们

    高级结果映射看官方网站

8 日志

8.1 日志工厂

查看异常,排错,日志工厂是最好的助手

以前:sout,debug

现在:日志工厂

image-20210619001943289

  • SLF4J

  • LOG4J【掌握】

  • LOG4J2

  • JDK_LOGGING

  • COMMONS_LOGGING

  • STDOUT_LOGGING【掌握】

  • NO_LOGGING

具体使用哪一个日志输出在设置中设定!

STDOUT_LOGGING标准日志输出

在核心配置文件里面配置

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

image-20210619002902864

8.2 Log4j

  1. 先导入log4j的包

    <!-- https://mvnrepository.com/artifact/log4j/log4j -->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    
    
  2. log4j配置文件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/wjj.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使用

    直接测试运行代码

    image-20210619005808660

  5. 简单使用

    1. 在要使用日志的类类中导入包import org.apache.log4j.Logger;

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

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

      logger.info("info");
      logger.debug("debug");
      logger.error("error");
      
    4. log文件

      image-20210619011022376

9. 分页

  • 减少数据的处理量

9.1 使用Limlt分页

  1. 接口

    //    分页
    List<User> getUserByLimit(Map<String,Object> map);
    
  2. 配置文件

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

    @Test
    public void getUserByLimit() {
        SqlSession sqlSession = MybatisUtil.getSqlSession();
    
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    
        HashMap<String, Object> map = new HashMap<>();
    
        map.put("startIndex", 2);
        map.put("pageSize", 2);
    
        List<User> userList = mapper.getUserByLimit(map);
    
        for (User user : userList) {
            System.out.println(user);
        }
        sqlSession.close();
    }
    

9.2 RowBounds分页

不再使用SQL实现分页

  1. 接口

    //    rowBounds
    List<User> getUserByRowBounds();
    
  2. 配置文件

    <!--    RowBounds分页-->
    <select id="getUserByRowBounds" resultMap="UserMap" resultType="User">
        select * from mybatis.user
    </select>
    
  3. 测试

    @Test
    public void getUserByRowBounds(){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
    
        RowBounds rowBounds = new RowBounds(1, 2);
    
        List<User> userList = sqlSession.selectList("com.mybatis.Mapper.UserMapper.getUserByRowBounds",null,rowBounds);
    
        for (User user : userList) {
            System.out.println(user);
        }
        sqlSession.close();
    }
    

9.3 分页插件

image-20210619020301614

10. 使用注解开发

10.1 面向接口编程

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

关于接口的理解

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

三个面向区别

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

10.2 使用注解

  1. 注解再接口上实现

    @Select("select * from user")
    List<User> getUserByList();
    
  2. 需要在核心配置文件中绑定接口!

    <!--    绑定接口-->
    <mappers>
        <mapper class="com.mybatis.Mapper.UserMapper"/>
    </mappers>
    
  3. 测试,与其他无异

本质:反射机制实现

**底层:**动态代理!

mybatis执行流程!!!!

img

10.3 CRUD

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

package com.mybatis.uitls;

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 MybatisUtil {
    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();
        }
    }

//设置为true,实现事务自动提交
    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession(true);
    }
}

查: 注解Param的id对应 #里面的id

//方法如果存在多个参数,所有参数前面必须加上Param()注解   基本类型才需要加
@Select("select * from user where id = #{id}")
User getUserById(@Param("id") int id);

增:

 @Insert("insert into user(id,name,pwd) values (#{id},#{name},#{password})")
int addUser(User user);

改:

@Update("update user set name = #{name},pwd = #{password} where id = #{id} ")
int updateUser(User user);

删:

@Delete("delete from user where id = #{uid}")
int deleteUser(@Param("uid") int id);

**注意:**关于@param()注解

  • 基本类型和String类型。需要加上
  • 引用类型不用
  • 如果只由应该基本类型,可以忽略,但是建议加上
  • 如果使用了这个,那么在SQL语句用的就是@param中设定的属性名

#{} 和 ${} 区别就是 一个是直接使用,一个预编译,$不安全

11. Lombok(尽量别用)

  1. 卸载lombok插件

  2. 导入依赖

    <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.20</version>
        <scope>provided</scope>
    </dependency>
    
  3. 在实体类上加注解

    • 类上加是作用全部参数
    • 参数上加是作用当前参数

@Data:无参构造,get.set,hashCode,toString,equals…

@AllArgsConstructor:有参构造

@NoArgsConstructor:无参构造

@Getter and @Setter

@ToString

@EqualsAndHashCode

12. 多对一的处理

对于多而言:关联【多对一】

对于一而言:集合 【一对多】

image-20210620015136778

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=utf8INSERT 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);

12.1 测试环境搭建

  1. 新建实体类Teacher Student

  2. 建立Mapper接口

  3. 建立Mapper.XML文件

    image-20210620170300224

  4. 在核心配置文件中注册Mapper接口或XML文件

  5. ce测试是否成功

12.2 多对一

  1. 按照查询嵌套处理
<mapper namespace="com.mybatis.Mapper.StudentMapper">
    <select id="getStudent" resultMap="Student">
        select *
        from mybatis.student
    </select>

    <!--    使用结果集映射  -->
    <resultMap id="Student" type="Student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <!--        复杂的属性需要单独处理
                    association 对象使用
                    collection  集合使用
        -->
        <!--        javaType另外一个连接的实体类  select另外一个实体类的查询语句-->
        <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
    </resultMap>

    <select id="getTeacher" resultType="Teacher">
        select *
        from mybatis.teacher
        where id = #{id};
    </select>
  1. 按照结构嵌套查询
<!--按照结果嵌套查询-->

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

<!--    取别名后,列对应的就是别名-->
<resultMap id="StudentTeacher" type="Student">
    <result property="id" column="sid"/>
    <result property="name" column="sname"/>
    <association property="teacher" javaType="Teacher">
        <result property="name" column="tname"/>
    </association>
</resultMap>

多对一查询方式:

  • 子查询
  • 联表查询

13. 一对多

比如:一个老师对应多个学生

老师实体类:

package com.mybatis.pojo;

import java.util.List;

public class Teacher {
    private Integer id;
    private String name;

    //    一个老师拥有多个学生
    private List<Student> students;
}

学生实体类:

package com.mybatis.pojo;

public class Student {
    private Integer id;
    private String name;
    private Integer id;
}

查询:

第一种:按结果查询

<select id="getTeacher" resultMap="Teacher">
select s.id sid, s.name sname, t.name tname, t.id tid
from mybatis.teacher t,
mybatis.student s
where s.tid = t.id
and t.id = #{id};
</select>

<resultMap id="Teacher" type="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<!--        javaType="" 指定属性的类型
集合中的泛型使用ofType获取-->
<collection property="students" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>

第二种:按查询嵌套

<select id="getTeacher2" resultMap="Teacher1">
    select *
    from mybatis.teacher
    where id = #{tid}
</select>

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


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

小结:

  1. 关联 — association【多对一】
  2. 集合 — collection 【一对多】
  3. javaType & ofType
    1. javaType 用来指定实体类中属性的类型
    2. ofType 用来指定泛型类型

注意点:

  1. 保证SQL可读性
  2. 注意一对多和多对一的属性字段问题
  3. 不好排查,可以使用日志

14. 动态SQL

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

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

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

14.1 搭建环境

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

实体类:

import java.util.Date;
@Data
public class Blog {
    private Integer id;
    private String title;
    private String author;
    private Date create_time;
    private Integer views;
}

随机ID工具类:

package com.mybatis.pojo;

import lombok.Data;

import java.util.Date;
@Data
public class Blog {
    private String id;
    private String title;
    private String author;
    private Date createTime;//属性名字和字段名字不一致
    private Integer views;
}

IF:同java程序的判断无异

<select id="queryBlog" resultType="blog" parameterType="map">
    select *
    from mybatis.blog
    where 1 = 1
    # test 里面写表达式
    <if test=" title != null ">
        and title = #{title}
    </if>
    <if test=" author != null ">
        and author = #{author}
    </if>
</select>

choose、when、otherwise:同switch

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

只要有一个成立就立即执行,其他就算处理也不要会执行

trim、where、set

where:尽量使用标签where

where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。

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

set:写的时候记得加“

set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。

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

trim:可以自定义的

动态SQL本质就是写逻辑语句

Foreach

@SuppressWarnings("all") //抑制警告

image-20210621010802106

# 通过万能的map集合,把集合传过来 open开头 separator中间|分隔符 close结尾

#{id}为item的id

and后面记得空格

不用map也可以 ,直接传list
<select id="queryBlogForeach" parameterType="map" resultType="blog">
    select * from mybatis.blog
    <where>

        <foreach collection="ids" item="id" index="index" open="and (" separator="or" close=")">

            id = #{id}
        </foreach>


    </where>
</select>
</mapper>
@Test
public void test1(){
    final SqlSession sqlSession = MybatisUtil.getSqlSession();
    final BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
    final HashMap map = new HashMap();

    final ArrayList<Integer> ids = new ArrayList<>();
    ids.add(1);
    ids.add(2);
    map.put("ids", ids);
    final List<Blog> blogs = mapper.queryBlogForeach(map);

    for (Blog blog : blogs) {
        System.out.println(blog);
    }
}

SQL片段

会将一些公共的抽取出来,实现代码的复用

sql标签抽取公共部分

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

include在需要使用的地方进行引用

# 引用SQL片段
<include refid="if"></include>

注意:

  • 尽量不要在多表查询的情况下使用
  • 不要存在where标签

动态SQL就是在拼接SQL语句,我们要保证SQL语句正确,按照SQL的格式取排列就行了

建议:

  • 先在mysql中写出完整语句,然后再慢慢拼接

15. 缓存

15.1 简介

注:Mybatis是半自动的持久化框架,灵活性更高
Hibernate是全自动的持久化框架

1.什么是缓存

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

2.为什么使用缓存

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

3.什么样的数据能使用缓存?

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

15.2 Mybatis缓存

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

多个数据库保持一致性需要遵循主从复制和读写分离

15.3 一级缓存

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

测试步骤:

  1. 开启日志
  2. 在一个SqlSession中查询两次系统记录
  3. 查看日志输出

缓存失效的情况:

  • 查询不同的东西

  • 增删改操作,可能会改变依赖的数据,所以会刷新缓存

  • 查询不同的mapper.xml

  • 手动清理缓存

sqlSession.clearCache();

15.4 二级缓存

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

步骤:

  1. 开启全局缓存

    <settings>
    
        <!--        开启全局缓存-->
        <setting name="cacheEnabled" value="true"/>
    </settings>
    
  2. 在mapper.xml文件里面使用

    image-20210621164348516

    也可以自定义参数

    <cache
      eviction="FIFO"
      flushInterval="60000"
      size="512"
      readOnly="true"/>
    
  3. 测试

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

      Error serializing object. Cause: java.io.NotSerializableException: com.mybatis.pojo.User

      public class User implements Serializable {}
      
  4. 小结

    • 只要开启了二级缓存,在同一个mapper有效
    • 所有数据会先存在一级缓存中
    • 只有会话提交或关闭时,才会提交到二级缓存

    15.5 缓存原理

img

15.6 自定义缓存(ehcache)

  1. 导入依赖

    <!--导入ehcache驱动-->
    <dependency>
        <groupId>org.mybatis.caches</groupId>
        <artifactId>mybatis-ehcache</artifactId>
        <version>1.1.0</version>
    </dependency>
    
  2. 使用,在mapper.xml 里面

    <cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
    
  3. 创建一个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>
    
  4. 一般报错是测试类写错了,会话用到同一个

posted @ 2022-03-30 19:04  Tzeao  阅读(45)  评论(0)    收藏  举报