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

    MyBatis

    第一个Mybatis程序

    思路:搭建环境-->导入MyBatis-->编写代码-->测试

    搭建环境

    1. 搭建数据库

    2. 新建项目

      • 新建一个maven项目(父)

      • 删除src目录

      • 导入maven依赖

         		<!--mysql驱动-->
                <dependency>
                    <groupId>mysql</groupId>
                    <artifactId>mysql-connector-java</artifactId>
                    <version>5.1.47</version>
                </dependency>
                <!--mybatis-->
                <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
                <dependency>
                    <groupId>org.mybatis</groupId>
                    <artifactId>mybatis</artifactId>
                    <version>3.5.2</version>
                </dependency>
                <!--junit-->
                <dependency>
                    <groupId>junit</groupId>
                    <artifactId>junit</artifactId>
                    <version>4.12</version>
                </dependency>
        
      • 创建子maven模块

    3. 编写mybatis核心配置文件

      • 链接数据库,URL中加入?serverTimezone=GMT

        jdbc:mysql://localhost:3306?serverTimezone=GMT
        
      <?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.jdbc.Driver"/>
                      <property name="url" value="jdbc:mysql://localhost:3306?serverTimezone=GMT&amp;useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                      <property name="username" value="root"/>
                      <property name="password" value="root"/>
                  </dataSource>
              </environment>
          </environments>
      
      </configuration>
      
    4. 编写mybatis工具类

      //sqlSessionFactory --> 工厂模式来构建sqlSession
      public class MybatisUtils {
      
          private static SqlSessionFactory sqlSessionFactory;
      
          static {
              try {
                  //获取sqlSessionFactory对象
                  String resource = "mybatis-01/src/main/resources/mybatis-config.xml";
                  InputStream inputStream = Resources.getResourceAsStream(resource);
                  sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      
          //既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
          public static SqlSession getSqlSession(){
              return sqlSessionFactory.openSession();
          }
      
      }
      
    5. 编写代码

      • 实体类 pojo
      • Mapper接口
      • 接口实现类由impl转换为mapper.xml配置文件
    6. 测试

      @Test
          public void test(){
              //获得sqlSession对象
              SqlSession sqlSession = MybatisUtils.getSqlSession();
              //执行sql
              UserMapper mapper = sqlSession.getMapper(UserMapper.class);
              List<user> userList = mapper.getUserList();
              //增删改需要提交事务
              sqlSession.commit();
              
              sqlSession.close();
          }
      

    万能的Map

    如果实体类或数据库表字段或者参数过多,我们应当考虑使用Map~

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

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

    传递模糊查询的方式

    1. 在Java代码执行的时候,传递通配符%%。

      List<user> users = mapper.getUserLike("%李%");
      
    2. 在sql拼接中使用通配符。

      SELECT * FROM tablename WHERE name like "%"#{name}"%"
      

    配置解析

    核心配置文件

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

    环境配置

    • Mybatis可以配置成适应多种环境,但每个SqlSessionFactory实例只能选择一种环境。
    • Mybatis默认的事务管理就是JDBC、连接池是POOLED

    属性(properties)

    1. 可以使用properties引用配置文件(db.properties)
    driver=com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3306?serverTimezone=GMT&useSSL=true&useUnicode=true&characterEncoding=UTF-8
    username=root
    password=root
    
    1. 引入配置文件
     <properties resource="db.properties">
         <!--property标签可写可不写,和db.properties中账号密码相同-->
            <property name="username" value="root"/>
            <property name="psd" value="root"/>
      </properties>
    
    • 可直接引入外部文件
    • 可增加一些属性配置
    • 如果两个文件有同一字段,优先使用外部配置文件

    类型别名

    • 类型别名是为Java类型设置一个短的名字。

    • 存在的意义仅用来减少完全限定名的冗余。

      	<!--给实体类起别名-->
      	<typeAliases>
             <typeAlias type="com.sx.pojo.user" alias="user"/>
          </typeAliases>
      
    • 也可以指定一个包名,MyBatis会在包名下面搜索需要的JavaBean,扫描到的实体类的包,它的默认别名就为这个类的类名首字母小写。

      	<typeAliases>
              <package name="com.sx.pojo"/>
          </typeAliases>
      
    • 基本类型的别名为_基本类型,包装类别名为首字母小写。

    映射器(Mappers)

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

     <!--Mapper.xml文件绑定-->
        <mappers>
            <mapper resource="comsxdaoUserMapper.xml"/>
        </mappers>
    

    生命周期和作用域

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

    1. 程序执行
    2. 根据mybatis-config.xml配置文件读取到SqlSessionFactoryBulider(建造者模式)
    3. SqlSessionFactoryBulider建造工厂SqlSessionFactory
    4. SqlSessionFactory工厂生产SqlSession
    5. SqlSession可以拿到Mapper(getMapper)
    6. 根据Mapper执行SQL
    7. 程序结束

    SqlSessionFactoryBulider:

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

    SqlSessionFactory:

    • 说白了就是可以想象为数据库连接池。
    • 一旦被创建就会在应用运行期间一直存在,没有任何理由丢弃它或者重新创建另一个实例。
    • SqlSessionFactory最佳的作用域就是应用作用域(程序开始就开始,程序结束就结束)。
    • 最简单的就是使用单例模式或静态单例模式。

    SqlSession:

    • 连接到连接池的一个请求!
    • SqlSession的实例不是安全的,不能被共享,所以其最佳作用域为请求或方法作用域。
    • 用完后需要赶紧关闭,否则资源被占用。

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

    resultMap结果集映射

        <!-- 映射结果集-->
        <resultMap id="user" type="user">
            <!--column数据库中的字段,property实体类中的属性-->
            <result column="id" property="id"/>
            <result column="name" property="name"/>
            <result column="pwd" property="password"/>
        </resultMap>
    
         <select id="allUser" resultMap="user">
         select * from mybatis.user
         </select>
    
    • resultMap id对应select resultMap。
    • resultMap type对应pojo 路径。
    • result column对应数据库字段名。
    • result property对应pojo属性名。
    • 属性名和数据库字段名相同可以省略。

    日志

    日志工厂

    如果一个数据库操作出现了异常,我们需要排错。日志是最好的助手!具体需要哪个可以在mybatis中设置。

    • SLF4J
    • LOG4J 【掌握】
    • LOG4J2
    • JDK_LOGGING
    • COMMONS_LOGGING
    • STDOUT_LOGGING 【掌握】标准的日志工厂的实现
    • NO_LOGGING

    LOG4J

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

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

      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/kuang.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>
      

    分页

    • 减少数据处理量

    limit

       <select id="limitUser" parameterType="map" resultMap="user">
             select * from mybatis.user limit #{startIndex},#{pageSize}
        </select>
    
     HashMap<String, Integer> Map = new HashMap<String, Integer>();
            Map.put("startIndex",0);
            Map.put("pageSize",2);
            List<user> users = mapper.limitUser(Map);
    

    使用注解开发

    • 注解直接在接口上实现

      public interface UserMappers {
         @Select("select * from mybatis.user")
         List<user> aLLUser();
      }
      
    • 需要在核心配置文件中绑定接口

      	<mappers>
              <mapper class="sx.dao.UserMappers"/>
          </mappers>
      

    本质:使用反射机制实现,底层使用了动态代理。

    Lombok

    • 在IDEA中安装Lombok插件。

    • 在项目中导入lombok的maven依赖。

      		<dependency>
                  <groupId>org.projectlombok</groupId>
                  <artifactId>lombok</artifactId>
                  <version>1.18.10</version>
                  <scope>provided</scope>
              </dependency>
      
    @ToString
    @EqualsAndHashCode
    @AllArgsConstructor //有参构造
    @NoArgsConstructor  //无参构造
    @Data  //无参构造,get set tostring hashcode equals
    

    关于@Param()注解

    • 基本类型参数或String类型参数需要加。
    • 引用类型不需要加。
    • 只有一个基本类型可忽略。
    • SQL中#{xxx}中引用的属性名就是@Param("xxx")中设定的属性名。

    多对一处理

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

    按照查询嵌套处理

     <!--1 查询所有的学生信息
            2 根据查询出来的学生tid,寻找对应老师
        -->
        <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="getStudent" resultMap="StudentTeacher">
    
            select * from mybatis.student
    
        </select>
    
        <select id="getTeacher" resultType="Teacher">
            select * from mybatis.teacher where id = #{id}
        </select>
    

    按照结果嵌套查询

    @Data
    public class Student {
        private int id;
        private String name;
    
        //学生需要关联一个老师
        private Teacher teacher;
    }
    
    <resultMap id="getStudent02" type="Student">
            <result column="sid" property="id"/>
            <result column="sname" property="name"/>
            <association property="teacher" javaType="Teacher">
                <result property="name" column="tname"/>
            </association>
        </resultMap>
    
        <select id="getStudent02" resultMap="getStudent02">
    
            select mybatis.student.id as sid,mybatis.student.name as sname,mybatis.teacher.name as tname
            from mybatis.student,mybatis.teacher
            where student.tid = teacher.id
    
        </select>
    
    • column:数据库中的列名或别名。
    • property:pojo下的属性名。
    • association:对象。
    • collection:集合。

    一对多处理

    1. 一个老师拥有多个学生。对于老师而言就是一对多的关系。
    @Data
    public class Teacher {
        private int id;
        private String name;
        //一个老师拥有多个学生
        private List<Student> students;
    }
    
    <resultMap id="TeacherStu" type="Teacher">
            <result column="tid" property="id"/>
            <result column="tname" property="name"/>
            <!--集合使用collection标签,
            javaType:指属性类型,不包含集合
            集合类型使用 ofType
            -->
            <collection property="students" ofType="Student">
                <result column="sname" property="name"/>
            </collection>
        </resultMap>
        <select id="getTeacher" resultMap="TeacherStu">
           select mybatis.teacher.name as tname,mybatis.teacher.id as tid,mybatis.student.name as sname
           from mybatis.teacher,mybatis.student
           where student.tid = teacher.id and teacher.id = #{tid}
        </select>
    

    小结

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

    注意点:

    • 保证sql可读性
    • 注意一对多和多对一的属性名字段问题

    动态SQL

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

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

    if

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

    choose(when,otherwise)

    <select id="queryBlogChoose" parameterType="map" resultType="blog">
             select * from mybatis.blog
             <where>
                 <choose>
                     <!--当when内test成立,执行拼接when内语句-->
                     <when test="title != null">
                       title = #{title}
                      </when>
                      <when test="author != null">
                         author = #{author}
                      </when>
                      <otherwise>
                         views = #{views}
                      </otherwise>
               </choose>
             </where>
        </select>
    
    • 当when内test成立,执行拼接when内语句,并跳过其他语句。
    • 当when内语句都不符合时,执行otherwise标签内sql

    trim(where,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>
    
    • set会动态判断修改的内容,可以自动去掉多余的逗号

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

    SQL片段

    有的时候我们可能会将一些公共的部分抽取出来,方便复用。

      	<sql id="if-title-author">
            <if test="title!=null">
                and title = #{title}
            </if>
            <if test="author!=null">
                and author = #{author}
            </if>
        </sql>
    
    	<select id="queryBlogIf" parameterType="map" resultType="blog">
            select * from mybatis.blog
            <where>
            <include refid="if-title-author"/>
            </where>
        </select>
    
    • 利用sql标签将公共sql提取出来。
    • 在需要的地方引入include标签,在refid匹配sql标签中的id即可引用公共sql。
    • 最好基于单表定义SQL片段。
    • where标签和set标签不要放在公共sql中。

    foreach

     <!--现在传以一个万能的map,这个map中可以存在一个集合-->
        <select id="blogById" parameterType="map" resultType="blog">
            select * from mybatis.blog
            <where>
            <foreach collection="ids" item="id" open="and ("  separator="or" close=")">
                id = #{id}
            </foreach>
            </where>
        </select>
    
    • 利用foreach标签遍历传入的值,让上面代码等同于

      select * from mybatis.blog where 1 = 1 and(id = 1 or id = 2 or id = 3);
      
    • 将(id = 1 or id = 2 or id = 3)放入一个集合传递给select标签。

    • foreach标签中的collection为集合名

    • item为遍历出的结果。(#{id}同款)

    • open为拼接的首个符号

    • close为拼接的末尾符号

    • separator为遍历出数据的分隔符

    动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列就可以了

    使用时利用可视化工具写出sql,再从xml中拼接出相同的sql

    缓存

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

    MyBatis缓存

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

    一级缓存

    • 一级缓存默认开启。

    • 一级缓存也叫本地缓存SqlSession

      • 与数据库同一次会话期间查询到的数据会放在本地缓存中。
      • 以后如果需要获取相同数据,直接从本地缓存拿,没有必要再次调用数据库。
    • 测试步骤:

      • 开启日志。
      • 测试在一个Session中查询两次相同的记录。
      • 查看日志输出即可看出两次记录仅访问了一次数据库。
    • 缓存失效的情况:

      • 查询不同的东西。
      • 对数据进行了增删改操作(即使不是缓存了的数据)。
      • 查询不同的Mapper.xml。
      • 手动清除缓存(clearCache())。

    二级缓存

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

    步骤:

    1. 开启全局缓存

      <settings>     
      	<setting name="cacheEnabled" value="true"/>
      </settings>
      
    2. 使用二级缓存

      <!--在当前mapper.xml中开启二级缓存-->
          <cache eviction="FIFO"
                 flushInterval="60000"
                 size="512"
                 readOnly="true"/>
      <!--一般可以不写标签参数-->
      

    小节:

    • 只要开启了二级缓存,在同一和mapper就有效。
    • 所有数据都会先放在一级缓存中。
    • 只有当前会话提交,或者关闭时,才会提交到二级缓存中。
  • 相关阅读:
    数仓1.3 |行为数据| 业务数据需求
    数仓1.1 |概述| 集群环境搭建
    麒麟Kylin
    ng--todolist
    mysql必知必会--用正则表达式 进行搜索
    mysql必知必会--用通配符进行过滤
    mysql必知必会--数 据 过 滤
    mysql必知必会--过 滤 数 据
    mysql必知必会--排序检索数据
    mysql必知必会--检 索 数 据
  • 原文地址:https://www.cnblogs.com/sxblogs/p/12976939.html
Copyright © 2011-2022 走看看