MyBatis 笔记

MyBatis

1.0 简介

1.1 什么是 MyBatis?

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

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

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

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

  • MyBatis本是apache的一个开源项目Batis,2010年这个项目由apache software foundation迁移到了google code,并且改名为MyBatis。

  • 2013年11月迁移到Github。

1.2 持久化

数据持久化

  • 持久化就是将程序的数据在持久状态和瞬时状态转化的过程

    • 例如把数据(如内存)保存到可永久保存的存储设备中(如磁盘)。

  • 内存:断电即失

  • JDBC就是一种持久化机制。文件IO也是一种持久化机制。

  • 数据库是对数据进行持久化的载体

  • 狭义的理解: “持久化”仅仅指把域对象永久保存到数据库中;广义的理解,“持久化”包括和数据库相关的各种操作。

    • 保存:把域对象永久保存到数据库。

    • 更新:更新数据库中域对象的状态。

    • 删除:从数据库中删除一个域对象。

    • 加载:根据特定的OID,把一个域对象从数据库加载到内存。

    • 查询:根据特定的查询条件,把符合查询条件的一个或多个域对象从数据库加载内在存中。

为什么需要持久化?

  • 持久化技术封装了数据访问细节,为大部分业务逻辑提供面向对象的API

    • 通过持久化技术可以减少访问数据库数据次数,增加应用程序执行速度

    • 代码重用性高,能够完成大部分数据库操作

    • 松散耦合,使持久化不依赖于底层数据库和上层业务逻辑实现,更换数据库时只需修改配置文件而不用修改代码

1.3 持久层

持久层:数据库交互

  • 也就是我们是常说的dao层。负责数据持久化。

  • 持久层就是和数据库交互,对数据库表进行曾删改查的。

原文:java中框架的概述(表现层、业务层、持久层的关系)_控制层业务层持久层的关系-CSDN博客

1.4 为什么需要MyBatis?

  • 传统的 JDBC 代码太复杂

  • SQL和代码的分离,提高了可维护性

  • 提供映射标签,支持对象与数据库的orm字段关系映射

  • 提供对象关系映射标签,支持对象关系组建维护

  • 提供xml标签,支持编写动态SQL

2.0 第一个MyBatis程序

2.1 搭建环境

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

  2. 删除src目录

  3. 导入maven依赖

2.2 创建一个模块

  • 编写mybatis的核心配置文件(入门_MyBatis中文网

  • 编写mybatis的工具类

     

    //sqlSessionFactory - - > sqlSession
    public class MybatisUtils {
        private static SqlSessionFactory sqlSessionFactory;
        static {
            try {
                // 使用Mybatis 第一获取sqlSessionFactory 对象
                String resource = "mybatis-config.xml";
                InputStream stream = Resources.getResourceAsStream(resource);
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
        // SqlSession 提供了在数据库执行 SQL 命令所需的所有方法
        public static SqlSession getSqlSession() {
            return sqlSessionFactory.openSession();
        }
    }

2.3 编写代码

  • 接口实现类 (由原来的UserDaoImpl转变为一个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/Mapper接口-->
    <mapper namespace="com.hunter.dao.UserDao">
    <!--    查询语句-->
        <select id="getUserList" resultType="com.hunter.pojo.User">
            select * from mybatis.user
        </select>
        <select id="selectBlog" resultType="Blog">
            select * from Blog where id = #{id}
        </select>
    </mapper>
  • Dao接口

     

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

2.4 测试

junit测试

 

public class UserDaoTest {
    @Test
    public void test(){
        //第一步:获得SqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //执行SQL
        UserDao userDao= sqlSession.getMapper(UserDao.class);
        List<User> userList = userDao.getUserList();
        for(User user : userList){
            System.out.println(user);
        }
        //关闭sqlSession
        sqlSession.close();
    }
}

问题1:ssl问题

解决:把jdbc中的url的ssl改为false

错误信息表明在尝试使用SSL/TLS连接MySQL数据库服务器时出现了问题,具体是由于证书验证问题导致的SSL握手异常。这种情况通常发生在应用程序尝试通过SSL与MySQL服务器通信但遇到自签名或不受信任的证书时。

  • 具体解决:暂时禁用SSL: 如果您正在测试并且只想快速解决问题,可以通过在JDBC URL中添加useSSL=false参数来临时禁用SSL。但是,请注意,在生产环境中不推荐这样做,因为它将通过明文传输数据。

问题2:由于maven的约定大于配置,我们之后可能遇到我们写的配置文件,无法被导出或者生效的问题

  • 解决:写在pom.xml

     

    <!--  在bunld中配置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>

3.0 CRUD

3.1 namespace

namespace中的包名要和mapper接口的包名一致!

3.2 CRUD

  • Id:就是对应的namespace中的方法名

  • resultType:SQL语句执行的返回值

  • parameterTyper:参数类型

  • ⚠️注意:增、删、改需要提交事务

    • sqlSession.commit();

1、select
  1. 编写接口

 

//根据ID查询用户
    User getUserById(int id);
  1. 编写对应的mapper中的SQL语句

 

<!--    根据ID查询用户-->
    <select id="getUserById" resultType="com.hunter.pojo.User" parameterType="int">
        select * from mybatis.user where id = #{id}
    </select>
  1. 测试

 

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

2、insert
  1. 编写接口

 

 
//插入一个用户
  int addUser(User user);
  1. 编写对应的mapper中的SQL语句

 

 
<!--    插入一个用户-->
    <insert id="addUser" parameterType="com.hunter.pojo.User">
        insert into mybatis.user(id, name, pwd) VALUES (#{id},#{name},#{pwd})
    </insert>
  1. 测试

 

 
    @Test
    public void addUser() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int user = mapper.addUser(new User(7, "deadcat2", "666"));
        if (user > 0) {
            System.out.println("插入成功!");
        }
        //提交事务
        sqlSession.commit();
        sqlSession.close();
    }

3、update
  1. 编写接口

//修改一个用户
    int updateUser(User user);
  1. 编写对应的mapper中的SQL语句

<!--    修改一个用户-->
    <update id="updateUser" parameterType="com.hunter.pojo.User">
        update  mybatis.user set name =#{name}, pwd=#{pwd} where id=#{id}
    </update>
  1. 测试

    @Test
    public void updateUser() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int user = mapper.updateUser(new User(7, "deadcatty", "999"));
        if (user > 0) {
            System.out.println("修改成功!");
        }
        sqlSession.commit();
        sqlSession.close();
    }

4、delete
  1. 编写接口

 //删除一个用户
    int deleteUser(int user);
  1. 编写对应的mapper中的SQL语句

<!--    删除一个用户-->
    <delete id="deleteUser" parameterType="int">
        delete from mybatis.user where id=#{id}
    </delete>
  1. 测试

   @Test
    public void deleteUser() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        int user = mapper.deleteUser(5);
        if (user > 0) {
            System.out.println("删除成功!");
        }
        sqlSession.commit();
        sqlSession.close();
    }

4.0 配置解析

4.1 核心配置文件

  • mybatis-config.xml

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

    • configuration(配置)

      • properties(属性)

      • settings(设置)

      • typeAliases(类型别名)

      • typeHandlers(类型处理器)

      • objectFactory(对象工厂)

      • plugins(插件)

      • environments(环境配置)

        • environment(环境变量)

          • transactionManager(事务管理器)

          • dataSource(数据源)

      • databaseIdProvider(数据库厂商标识)

4.2 环境配置(environments)

MyBatis可以配置成多种环境

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

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

4.3 属性(properties)

我们可以通过properties属性来实现引用配置文件

这些属性都是可以外部配置且动态替换的,既可以在典型的Java属性文件中配置(db.properties),也可以通过properties元素的子元素来传递。

  1. 编写一个配置文件。db.properties

    • 这里就是properties 元素中的 resource 属性读取类路径下属性文件

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8
username=root
password=123456789
  1. 在核心配置文件中映入

 

 
<!--    configuration 核心配置文件-->
<configuration>
  
        <!--   引入外部配置文件 -->
    <properties resource="db.properties">
         <!--   properties 元素体内指定的属性 -->
    <property name="username" value="dev_user"/>
    <property name="password" value="123456"/>
    </properties>
               ......
                <property name="driver" value="${driver}"/>
                <property name="url"  value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
               ......
  • 这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件(db.properties)中配置这些属性,也可以在 properties 元素的子元素中设置。

  • 如果一个属性在不只一个地方进行了配置,那么,MyBatis 将按照下面的顺序来加载:

    • 首先读取在 properties 元素体内指定的属性。

    • 然后根据 properties 元素中的 resource 属性读取类路径下属性文件,或根据 url 属性指定的路径读取属性文件,并覆盖之前读取过的同名属性。

    • 最后读取作为方法参数传递的属性,并覆盖之前读取过的同名属性。

    就近读,远处后来同名者居上

4.4 类型别名(typeAliases)

第一种:

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

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

 

 
<!--    可以给实体类起别名-->
    <typeAliases>
        <typeAlias type="com.hunter.pojo.User" alias="User"/>
    </typeAliases>

第二种:

  • 也可以指定一个包名,MyBatis会在包名下面搜索需要的 JavaBean

  • 扫描实体类的包,它的默认别名就为这个类的 类名,首字母小写,比如:

    <typeAliases>
        <package name="com.hunter.pojo"/>
    </typeAliases>

总结:

在实体类比较少的时候,使用第一种方式。

如果实体类十分多,建议使用第二种。

第一种可以DIY别名,第二种则需要通过在实体类(JavaBean)上增加注解

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

4.5 设置

详情见 官方文档:配置_MyBatis中文网

4.6 映射器(mappers)

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

方式一:使用相对于类路径的资源(resource)引用(推荐使用!)
<!--每一个Mapper.XML  都需要在Mybatis核心配置中注册!-->
<mappers>
  <mapper resource="com/hunter/dao/UserMapper.xml"/>
</mappers>

方式二:使用class文件绑定注册
<!--每一个Mapper.XML  都需要在Mybatis核心配置中注册!-->
<mappers>
  <mapper class="com.hunter.dao.UserMapper"/>
</mappers>

⚠️注意点:

  • 接口和他的Mapper配置文件必须同名

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

方式三:使用扫描包进行注入绑定
<mappers>
 <package name="com.hunter.dao"/>
</mappers> 

⚠️注意点:

  • 接口和他的Mapper配置文件必须同名

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

4.7 生命周期和作用域

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

SqlSessionFactoryBuilder:

  • 一旦创建SqlSessionFactory,就不再需要它了

  • 局部变量

SqlSessionFactory:

  • 可以想象为“数据库连接池

  • 一旦被创建就应该在应用的运行期间一直存在不能丢弃它也不能重新创建另一个

  • 因此 SqlSessionFactory 的最佳作用域是应用作用域(application)

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

SqlSession:

  • 连接到连接池的一个请求

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

  • 用完之后需要赶紧关闭,否则资源被占用

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

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

解决方法:

    1. 起别名

     

     
    <!--    根据ID查询用户-->
        <select id="getUserById" resultType="com.hunter.pojo.User" parameterType="int">
            select id,name,pwd as password mybatis.user where id = #{id}
        </select>
    1. 结果集映射(resultMap)

     

     
    <!--结果集映射-->
    <resultMap id="UserMap" type="User">
        <!--column数据库中的字段,property实体类中的属性-->
        <result column="id" property="id"/>
        <result column="name" property="name"/>
        <result column="pwd" property="password"/>
    </resultMap>
    <select id="getUserById" resultType="com.hunter.pojo.User" parameterType="int">
        select * from mybatis.user where id = #{id}
    </select>
    • resultMap 元素是 MyBatis 中最重要最强大的元素

    • resultMap 的设计思想是,对于简单的语句根本不需要配置显式的结果映射,而对于复杂一点的语句只需要描述它们的关系就行了

    • resultMap最优秀的地方在于,虽然你对它已经相当了解了,但是根本就不需要显式地用到他们。

6.0 日志

6.1 日志工厂

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

  • SLF4J

  • LOG4J (掌握)

  • LOG4J2

  • JDK_LOGGING

  • COMMONS_LOGGING

  • STDOUT_LOGGING (掌握)

  • NO_LOGGING

在Mybatis中具体使用哪一个日志实现,在设置中设定

STDOUT_LOGGING ——标准日志输出

<!--在mybatis核心配置文件中,配置我们的日志-->
<settings>
   <setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>

6.2 LOG4J

什么是LOG4J ?

  • LOG4J 是Apache的一个开源项目,通过使LOG4J,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件

  • 我们也可以控制每一条日志输出格式

  • 通过定义每一条信息的级别,我们能够更加细致地控制日志生成过程

  • 通过一个配置文件来灵活进行配置,而不需要修改应用的代码

7.0 分页

思考:为什么要分页?

  • 减少数据处理量

7.1 使用Iimit分页

语法:-- 每页有pageSize个,从startIndex开始查询
	   select * from `user` limit startIndex,pageSize;

		 -- [0,n]
		 select * from `user` limit n; 	

使用Mybatis实现分页

  1. 接口

    //分页
    List<User> getUserByLimit(Map<String, Integer> map);
  2. Mapper.xml

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

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

8.0 使用注解

8.1 面向接口编程

  • 大家之前都学习过面向对象编程,也学习过接口。但在真正的开发中,我们会选择面向接口编程

  • 根本原因:解耦,可拓展,提高复用,分层开发中,上层不用管具体的实现,大家都遵守共同的标准,使得开发变得容易,规范性更好

  • 在一个面向对象的系统中,系统各种功能室友许多不同的对象协作完成的。在这种情况下,各个对象内部是如何实现的,对系统设计人员来说就不那么重要了

  • 而各个对象之间的协作关系则成为系统设计的关键。小到不同类之间的通信,大到各模块之间的交互,在系统设计之初都是要着重考虑的,这也是系统设计的主要工作内容。面向接口编程就是按照这种思想来编程。

关于接口的理解

  • 接口从更深层次的理解,应该是定义与实现的分类。

  • 接口的本身反映了系统设计人员对系统的抽象理解。

    接口有两类:

    1. 对一个个体的抽象,它对应一个抽象体(abstract class)

    2. 对一个个体某一方面的抽象,即形成一个抽象(interface)

    • 一个个体可能有多个抽象面(interface)。

    • 抽象体(abstract class)和抽象面(interface)是有区别的。

三个面向的区别

  • 面向对象 是指,我们考虑问题时,以对象为单位,考虑它的属性以及方法。

  • 面向过程 是指,我们考虑问题时,以一个具体的流程(事务过程)为单位,考虑它的实现。

  • 接口设计 与 非接口设计 是针对复用技术而言的,与面向对象(过程)不是一个问题。更多是对系统整体的架构。

8.2 使用注解开发

  1. 注解在接口上实现

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

    <!--绑定接口-->
    <mappers>
       <mapper class="com.hunter.dao.UserMapper"/>
    </mappers>
  3. 测试

本质:反射机制实现

底层:动态代理

9.0 多对一处理

9.1 测试环境搭建

  1. 新建实体类Teacher,Student

  2. 新建Mapper接口

  3. 建立Mapper.XML文件

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

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

9.2 按照查询嵌套查询

 

 
<!--
    思路:
        1.  查询所有的学生信息
        2.  根据查询出来的学生的tid,寻找对应的老师
-->
    <select id="getStudent" 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>

9.3 按照结果嵌套查询

<!--    按照结果嵌套查询-->
    <select id="getStudent2" 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>

回顾MySQL多对一查询:

  • 子查询

  • 联表查询

10.0 一对多处理

比如:一个老师拥有多个学生

对于老师而已就是一对多的关系

实体类

 

 
//学生
public class Student {
    private int id;
    private String name;
    private int tid;
    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", tid=" + tid +
                '}';
    }
}
 

 
//老师
public class Teacher {
    private int id;
    private String name;
    @Override
    public String toString() {
        return "Teacher{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", students=" + students +
                '}';
    }
    // 一个老师拥有多个学生(添加学生的集合)
    private List<Student> students;
}

按照结果查询处理

<!--    按结果嵌套查询-->
    <select id="getTeacher" resultMap="TeacherStudent">
        select s.id sid, s.name sname, t.id tid, t.name `tname`
        from mybatis.student s,
             mybatis.teacher t
        where s.tid = t.id
          and t.id = #{tid}
    </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"/>
            <result property="tid" column="stid"/>
        </collection>
    </resultMap>

小结

  • 关联 - association(多对一)

  • 集合 - collection(一对多)

  • javaType & ofType

    • javaType 用来指定实体类中属性的类型

    • ofType 用来指定映射到 List 或者 集合中的 pojo 类型,泛型中的约束类型

⚠️注意点:

  • 保证SQL可读性

  • 注意一对多 和 多对一 中 ,属性名和字段的问题

11.0 动态SQL

11.1 什么是动态SQL?

动态SQL:根据不同的条件生存不同的SQL语句

动态 SQL 元素可能会感觉似曾相识。在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。

  • if

  • choose (when, otherwise)

  • trim (where, set)

  • foreach

11.2 搭建环境

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;

创建一个基础工程

  1. 导包

  2. 编写配置文件

     

     
    <mappers>
      <mapper class="com.hunter.dao.BlogMapper"/>
    </mappers>

  3. 编写实体类

     

     
    public class Blog {
        private String id;
        private String title;
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
        public String getTitle() {
            return title;
        }
        public void setTitle(String title) {
            this.title = title;
        }
        public String getAuthor() {
            return author;
        }
        public void setAuthor(String author) {
            this.author = author;
        }
        public Date getCreateTime() {
            return createTime;
        }
        public void setCreateTime(Date createTime) {
            this.createTime = createTime;
        }
        public int getViews() {
            return views;
        }
        public Blog() {
        }
        public Blog(String id, String title, String author, Date createTime, int views) {
            this.id = id;
            this.title = title;
            this.author = author;
            this.createTime = createTime;
            this.views = views;
        }
        public void setViews(int views) {
            this.views = views;
        }
        private String author;
        private Date createTime;
        private int views;
        @Override
        public String toString() {
            return "Blog{" +
                    "id='" + id + '\'' +
                    ", title='" + title + '\'' +
                    ", author='" + author + '\'' +
                    ", createTime=" + createTime +
                    ", views=" + views +
                    '}';
        }
    }

  4. 编写实体类对应的 Mapper接口 和 Mapper.xml 文件

public interface BlogMapper {
    //插入数据
    int addBlog(Blog blog);
}
<mapper namespace="com.hunter.dao.BlogMapper">
<insert id="addBlog" parameterType="Blog">
    insert into mybatis.blog(id, title, author, create_time, views)
    VALUES (#{id},#{title},#{author},#{createTime},#{views});
</insert>

11.3 IF

<!--    查询博客-->
    <select id="queryBlogIF" parameterType="map" resultType="com.hunter.pojo.Blog">
        select * from mybatis.blog 
      	<where> <!--where标签-->
        	<if test="title != null">
           	 	and title=#{title}
        	</if> 
        	<if test="author != null">
            	and author=#{author}
        	</if>
       </where> <!--where标签-->
    </select>

11.4 choose (when,otherwise) (有点像switch...case,只执行一个条件,第一个满足了,后面的条件就不执行)

我们不想使用所有的条件,而只是想从多个条件中选择一个使用

 

 
<!--    查询博客-->
    <select id="queryBlogIF" parameterType="map" resultType="com.hunter.pojo.Blog">
        select * from mybatis.blog
        <where>
        <choose>
            <when test="title != null">
                title = #{title}
            </when>
            <when test="author != null">
                and author = #{author}
            </when>
            <otherwise>
                and views = #{views}
            </otherwise>
        </choose>
        </where>
    </select>

11.5 trim (where, set)

 

 
        <where>
        <if test="title != null">
            and title=#{title}
        </if>
        <if test="author != null">
            and author=#{author}
        </if>
        </where>

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

if

where 、 set 、choose 、when

SQL片段

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

  1. 使用SQL标签抽取公共部分

 

 
<!--    SQL片段-->
<sql id="when-title-author-views">
        <choose>
            <when test="title != null">
                title = #{title}
            </when>
            <when test="author != null">
                and author = #{author}
            </when>
            <otherwise>
                and views = #{views}
            </otherwise>
        </choose>
    </sql>
  1. 在需要使用的地方使用include标签引用即可

 

 
<!--    查询博客-->
    <select id="queryBlogIF" parameterType="map" resultType="com.hunter.pojo.Blog">
        select * from mybatis.blog
        <where>
          <!--    include标签-->
            <include refid="when-title-author-views"></include>
        </where>
    </select>

⚠️ 注意事项:

  • 最好基于单表来定义SQL片段

  • 不要存在where标签

11.6 foreach

12.0 缓存

12.1 简介

 

 
查询:连接数据库,很消耗资源
把查询的结果,暂存在一个地方-->内存 :缓存
再次查询相同数据时,直接去缓存查询,不用再从数据库中查询

  1. 什么是缓存(cache)?

    • 存储在内存中的临时数据

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

  2. 为什么使用缓存?

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

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

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

12.2 Mybatis缓存

  • MyBatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率。

  • MyBatis系统中默认定义了两级缓存:一级缓存二级缓存

    • 默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)

    • 二级缓存需要手动开启和配置,它是基于namespace级别的缓存

    • 为了提高扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存

12.3 一级缓存

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

    • 与数据库同一次会话期间查询到的数据会放在本地缓存中

    • 以后如果需要获取相同的数据,直接从缓存中拿,没必要再去查询数据库

缓存失效的情况:

  1. 查询不同的东西

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

  3. 查询不同的Mapper.xml

  4. 手动清理缓存( SqlSession.clearCache( ) )

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

12.4 二级缓存

  • 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存

  • 基于namespace级别的缓存,一个namespace,对应一个二级缓存

  • 工作机制

    • 一个会话查询一条数据,这条数据就会放在当前会话的一级缓存中

    • 如果当前会话关闭了,这个会话对应的一级缓存就没了。但是我们需要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中

    • 新的会话查询信息,就可以从二级缓存中获取内容

    • 不同的mapper查询出的数据会放在自己的对应的缓存(map)中

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值