zoukankan      html  css  js  c++  java
  • Mybatis学习笔记

    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 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。
    • 2013年11月迁移到Github。

    如何获取mybatis?

    • Maven仓库

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

    2、第一个Mybatis

    2.1、搭建环境

    创建一个普通的maven项目,在里面再创建一个普通的maven子项目。

    导入依赖

    <dependencies>
        <!--    Mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <!--        mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!--        junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    

    2.2、编写JDBC配置文件

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <!--configuration核心配置文件-->
    <configuration>
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.jdbc.Driver"/>
                    <property name="url" value="jdbc:mysql://localhost:3306/mybatis?character=UTF-8&amp;useUnicode=true&amp;useSSL=true"/>
                    <property name="username" value="root"/>
                    <property name="password" value="123456"/>
                </dataSource>
            </environment>
        </environments>
    </configuration>
    

    2.3、编写工具类

    package com.Lv.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;
    
    /**
     * @Author: Lv
     * @Description:工具类
     * @Vision: 1.0
     * @Date: Created in 18:41 2020/7/28
     */
    public class MybatisUtils {
        private static SqlSessionFactory sqlSessionFactory;
        static {
            try {
                //获取sqlSessionFactory对象
                String resource = "com.Lv.resource/mybatis-config.xml";
                InputStream inputStream = Resources.getResourceAsStream(resource);
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        //获取sqlSessionFactory
        public SqlSession getSqlSession(){
            return sqlSessionFactory.openSession();
        }
    }
    

    2.4、实体类

    2.5、Dao层接口

    public interface UserDao {
        List<User> getUser();
    }
    

    2.6、Dao层实现类由原来的UserDaoImpl变为xml配置文件

    <?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.Lv.dao.UserDao">
        <select id="getUser" resultType="com.Lv.User">
            SELECT * FROM `user`
        </select>
    </mapper>
    

    2.7、测试

    注意点:每一个Mapper.xml文件都需在核心配置文件中配置

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

    Maven中资源生成或导出失败问题

    java.lang.ExceptionInInitializerError
    
    <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>
    

    3、CRUD

    1、namespace

    namespace中的包要和Dao/Mapper的包名一致

    2、select

    选择,查询语句:

    • id:就是对应namespace中的方法名;
    • resultType:SQL语句的返回值
    • parameterType:参数类型

    编写接口

    //根据id查询用户
    User getUser(int id);
    

    在UserMapper.xml中配置

    <select id="getUser" parameterType="int" resultType="com.Lv.pojo.User">
        select * from user where id=#{id}
    </select>
    

    测试

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

    3、insert

    <insert id="addUser" parameterType="com.Lv.pojo.User">
        insert into user values (#{id},#{name},#{pwd})
    </insert>
    
    @Test
    public void addUserTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    
        int i = mapper.addUser(new User(4, "丽丽", "555555555"));
    
        //增删改需要提交事务
        sqlSession.commit();
    
        sqlSession.close();
    }
    

    4、update

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

    5、delete

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

    注意点:增删改中需要提交事务

    4、万能的Map

    假设,我们的实体类,或者数据库中的表,字段或者参数过多,我们应当考虑使用Map

    //使用Map传参增加加一个用户
    int addUser2(Map<String,Object> map);
    
    <insert id="addUser2" parameterType="Map">
        insert into user values (#{userid},#{username},#{userpwd})
    </insert>
    
    @Test
    public void addUser2Test(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("userid",5);
        map.put("username","天天");
        map.put("userpwd","123456");
    
        int i = mapper.addUser2(map);
    
        sqlSession.commit();
        sqlSession.close();
    }
    

    Map传递参数,在SQL中取key即可

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

    参数只有一个基本数据类型的情况下,可以直接在SQL中取到,即参数类型可以忽略不写

    多个参数用Map或者注解

    4、配置解析

    1、核心配置文件

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

    2、环境配置(environments)

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

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

    3、属性(properties)

    编写一个配置文件

    driver=com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3306/mybatis?character=UTF-8&useUnicode=true&useSSL=true
    username=root
    password=123456
    

    在核心配置文件中引入

    注意:配置文件中个标签有顺序,严格按照顺序来

    <?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">
            <property name="username" value="aabb"/>
        </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>
    <!--    每一个Mapper都需要在核心配置文件中配置-->
        <mappers>
            <mapper resource="com/Lv/dao/UserMapper.xml"/>
        </mappers>
    </configuration>
    
    • 可以直接使用外部引入文件
    • 可以在其中增加一些属性配置
    • 如果两个文件有同一个字段,优先使用外部引入配置文件的。

    4、类型别名(typeAliases)

    • 类型别名可为 Java 类型设置一个缩写名字
    • 意在降低冗余的全限定类名书写

    第一种:

    <!--    为实体类取别名-->
    <typeAliases>
        <typeAlias type="com.Lv.pojo.User" alias="User"/>
    </typeAliases><typeAlias type="com.Lv.pojo.User" alias="User"/>
    

    第二种:

    • 也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean
    • 扫描实体类的包,它的默认别名就是实体类类名首字母小写
    <!--    为实体类取别名-->
    <typeAliases>
        <package name="com.Lv.pojo"/>
    </typeAliases>
    

    在实体类比较少的时候,用第一种

    在实体类比较多的时候用第二种

    区别:第一种可以DIY(自定义)别名,第二种则不行。如果非要改,需要在实体类上加注解。

    @Alias("user")
    

    5、设置

    这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为

    6、其他配置

    7、映射器(mappers)

    方式一:

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

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

    方式二:
    通过类名注册

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

    注意点:

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

    方式三:

    通过扫描包注册

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

    注意点:

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

    8、生命周期和作用域

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

    SqlSessionFactoryBuilder

    一旦创建了 SqlSessionFactory,就不再需要它了,因此 SqlSessionFactoryBuilder 实例的最佳作用域是方法作用域(也就是局部方法变量)

    SqlSessionFactory

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

    SqlSession

    • 每个线程都应该有它自己的 SqlSession 实例
    • SqlSession的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。
    • 关闭操作很重要

    这里的每一个Mapper就代表一个具体的业务!

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

    将不一致的属性名和字段名进行映射即可

        <select id="getStudent" resultMap="stu">
            select * from student
        </select>
        <resultMap id="stu" type="Student">
            <result property="pwd" column="password"/>
        </resultMap
    

    6、日志

    1、日志工厂

    logImpl:STDOUT_LOGGING LOG4J

    <!--    设置日志工厂-->
    <settings>
        <!--        标准日志工厂-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    

    2、log4j

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

    1、导包

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

    2、配置文件

    #newhappy  log4j.properties start
    log4j.rootLogger=DEBUG,myConsole,myLogFile
    #控制台输出的相关设置
    log4j.appender.myConsole=org.apache.log4j.ConsoleAppender
    log4j.appender.myConsole.layout=org.apache.log4j.PatternLayout
    log4j.appender.myConsole.layout.ConversionPattern=%5p [%t] (%F:%L) -%m%n
    log4j.appender.myConsole.threshold=DEBUG
    log4j.appender.myConsole.Target=System.out
    #文件输出的相关设置
    log4j.appender.myLogFile=org.apache.log4j.RollingFileAppender
    log4j.appender.myLogFile.File=./log/Lv.log
    log4j.appender.myLogFile.MaxFileSize=10mb
    log4j.appender.myLogFile.MaxBackupIndex=2
    log4j.appender.myLogFile.layout=org.apache.log4j.PatternLayout
    log4j.appender.myLogFile.layout.ConversionPattern=%d{mmm d,yyyy hh:mm:ss a} : %p [%t] %m%n
    log4j.appender.myLogFile.threshold=DEBUG
    #日志输出级别
    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
    #newhappy log4j.properties end
    

    3、配置日志工厂为LOG4J

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

    4、log4j的使用,运行刚才的测试

    简单使用

    1. 导包:import org.apache.log4j.Logger;

    2. 获得log4j

      static Logger logger = Logger.getLogger(UserMapperTest.class);
      
    3. 测试

          @Test
          public void log4jTest(){
              logger.info("info:进入log4jTest");
              logger.debug("debug:进入log4jTest");
              logger.error("error:进入log4jTest");
          }
      

    7、分页

    思考:为什么要分页?

    • 减少数据的处理量

    7.1、使用LImit分页

    语法:SELECT * FROM `user` LIMIT startidex,pagesize;
    

    接口

    List<User> getUsers(Map<String,Integer> map);
    

    Mapper配置文件

    <select id="getUsers" parameterType="map" resultType="User">
        SELECT * FROM `user` LIMIT #{startIndex},#{pageSize}
    </select>
    

    测试

        @Test
        public void getUsers(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    
            Map<String,Integer> map = new HashMap<String, Integer>();
            map.put("startIndex",1);
            map.put("pageSize",3);
    
            List<User> userList = mapper.getUsers(map);
    
            for (User user : userList) {
                System.out.println(user);
            }
    
            sqlSession.close();
        }
    

    7.2、RowBounds分页

    7.3、分页插件

    MyBatis分页插件PageHelper

    8、注解开发

    不需要在Mapper文件中配置,直接可以在接口上用注解,不过只能用于简单数据库操作

    示例:

    //根据id查询用户
    @Select("select * from user where id=#{id}")
    User getUser(@Param("id") int id);
    

    9、Lombok

    使用

    1. 在IDEA中安装Lombok插件

    2. 导入jar包

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

      @Data
      @AllArgsConstructor
      @NoArgsConstructor
      

    10、多对一处理

    1、数据库准备

    CREATE TABLE `teacher`(
    `id` INT(3) NOT NULL,
    `name` VARCHAR(20) NOT NULL,
    PRIMARY KEY (`id`)
    )ENGINE=INNODB DEFAULT CHARSET=utf8;
    
    INSERT INTO `teacher` VALUES (1,'Lv老师')
    
    CREATE TABLE `student`(
    `id` INT(4) NOT NULL,
    `name` VARCHAR(20),
    `tid` INT(3),
    PRIMARY KEY (`id`),
    KEY `fktid`(`tid`),
    CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
    )ENGINE=INNODB DEFAULT CHARSET=utf8;
    
    INSERT INTO `student` VALUES (1,'小明',1),(2,'小红',1),(3,'小蓝',1),(4,'小强',1),(5,'小黄',1)
    

    2、测试环境搭建

    1. 新建实体类Teacher,Student
    2. 建立Mapper接口
    3. 建立Mapper.xml文件
    4. 在核心配置文件中绑定注册我们的Mapper接口或文件
    5. 测试查询是否成功

    3、按照查询嵌套处理

    <!--    思路:
                   1、查询所有学生信息
                   2、根据获取的tid查询老师的信息
    -->
    <select id="getStudentInfo" 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`=#{id}
    </select>
    

    4、按照结果嵌套查询

    <!--    根据结果嵌套查询-->
    <select id="getStudentInfo2" resultMap="StudentTeacher2">
        SELECT s.`id` sid,s.`name` sname,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="name" column="tname"/>
        </association>
    </resultMap>
    

    11、一对多

    1、环境搭建

    public class Teacher {
        private Integer id;
        private String name;
        private List<Student> students;
    
    public class Student {
        private Integer id;
        private String name;
    
        private Integer tid;
    

    2、按照结果嵌套查询

    <!--根据结果嵌套查询-->
    <select id="getTeacher" resultMap="TeacherStudent">
        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="TeacherStudent" type="Teacher">
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>
        <!--复杂的查询,需要单独处理 对象:association  集合:collection
            JavaType="" 指定属性的类型
            集合中的泛型信息,用ofType获取
            -->
        <collection property="students" ofType="Student">
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
        </collection>
    </resultMap>
    

    3、子查询嵌套

    <!--子查询嵌套处理-->
    <select id="getTeacher2" resultMap="TeacherStudent2">
        select * from teacher where id=#{tid}
    </select>
    <resultMap id="TeacherStudent2" type="Teacher">
        <collection property="students" javaType="ArrayList" ofType="Student" column="id" select="getStudentBytid"/>
    </resultMap>
    <select id="getStudentBytid" resultType="Student">
        select * from student where tid=#{tid}
    </select>
    

    小结:

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

    注意点:

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

    面试必问

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

    12、动态SQL

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

    1、环境搭建

    数据库建表

    create table `blog` (
    	`id` varchar (150),
    	`title` varchar (150),
    	`author` varchar (150),
    	`create_time` datetime ,
    	`views` int (10)
    ); 
    

    编写实体类

    public class Blog {
        private String id;
        private String title;
        private String author;
        private Date createTime;
        private int views;
    

    编写实体类对应的Mapper

    插入数据测试

    //插入
    int addBlog(Blog blog);
    
    <insert id="addBlog" parameterType="blog">
        INSERT INTO `blog`(`id`,`title`,`author`,`create_time`,`views`) VALUES
        (#{id},#{title},#{author},#{createTime},#{views})
    </insert>
    
        @Test
        public void insertBlog(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
    
            Blog blog = new Blog();
            blog.setId(UUIDUntils.getId());
            blog.setTitle("我在学Mybatis...");
            blog.setAuthor("Lvvvvvvvvv");
            blog.setCreateTime(new Date());
            blog.setViews(9999);
            mapper.addBlog(blog);
    
            blog.setId(UUIDUntils.getId());
            blog.setTitle("Mybatis 不太难的亚子");
            mapper.addBlog(blog);
    
            blog.setId(UUIDUntils.getId());
            blog.setTitle("期待快学完框架");
            mapper.addBlog(blog);
    
            sqlSession.commit();
    
            sqlSession.close();
        }
    

    注意:增删改需要提交数据,增删改需要提交数据,增删改需要提交数据,重要的话讲三遍

    2、IF

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

    3、choose(when,otherwise)、

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

    4、trim(where,set)

    “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除

    SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。

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

    5、SQL片段

    我们可以像提取公共类一样,将公共SQL片段提取出来

    <sql id="query-title-author">
        <if test="author != null">
            and author=#{author}
        </if>
        <if test="title != null">
            and title=#{title}
        </if>
    </sql>
    
    <select id="queryBlog" resultType="Blog" parameterType="map">
        select * from blog
        <where>
            <include refid="query-title-author"></include>
        </where>
    </select>
    

    6、ForEach

    接口

    //ForEach查询
    List<Blog> queryByForEach(Map map);
    

    Mapper.xml

    <select id="queryByForEach" parameterType="map" resultType="Blog">
        select * from blog
        <where>
            <foreach collection="ids" item="id" open="and (" close=")" separator="or">
                id=#{id}
            </foreach>
        </where>
    </select>
    

    测试

    @Test
    public void queryByForeach(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
    
        List<String> ids = new ArrayList<String>();
        ids.add("1");
        ids.add("2");
        ids.add("3");
    
        Map map = new HashMap();
        map.put("ids",ids);
    
        List<Blog> blogs = mapper.queryByForEach(map);
    
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
    
        sqlSession.close();
    }
    

    13、缓存

    1、简介

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

    2、Mybatis缓存

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

    3、一级缓存

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

    测试步骤:

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

    缓存失效的情况:

    1. 查询不同的东西
    2. 增删改操作,可能会改变原来的数据,所以必定会刷新缓存
    3. 查询不同的Mapper.xml
    4. 手动清理换缓存

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

    一级缓存相当于一个Map,用完即失。

    4、二级缓存

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

    步骤:

    1. 虽然全局缓存默认开启,但还是在核心配置文件中显式开启全局缓存

      <!--        开启二级缓存-->
      <setting name="cacheEnabled" value="true"/>
      
    2. 在需要的Mapper中开启缓存

    1. 测试

      • 问题:我们需要将相应的实体类序列化,不然会报以下错
      java.io.NotSerializableException: com.Lv.pojo.Blog
      

      实体类序列化

    小结:

    • 只要开启了二级缓存,在同一个Mapper中就有效
    • 所有的数据都会暂时放到一级缓存
    • 只有当会话提交或关闭的时候,才会提交到二级缓存
  • 相关阅读:
    【JavaP6大纲】MySQL篇:如何实现 MySQL 的读写分离?MySQL 主从复制原理是啥?如何解决 MySQL 主从同步的延时问题?
    【JavaP6大纲】MySQL篇:现在有一个未分库分表的系统,未来要分库分表,如何设计才可以让系统从未分库分表动态切换到分库分表上?
    快速搭建PHP开发环境(PhpStorm+EasyPHP)
    iBatis开发者手册翻译(目录)
    iBatis开发者手册翻译(章节一、引言)
    asp.net 数据操作三步曲(一) :)
    一事归一事
    闲言碎语话心得你给我多少钱
    研发过程之代码评审
    让她自己来
  • 原文地址:https://www.cnblogs.com/Lv-orange/p/13418162.html
Copyright © 2011-2022 走看看