Mybatis

1.简介

1.1 什么是Mybatis

Mybatis是一款优秀的持久层框架,支持定制化SQL、存储过程以及高级映射。Mybatis是Apache的一个开源项目,现迁移到GitHub。

如何获得Mybatis:1.Maven;2.GitHub

1.2 持久化

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

1.3 持久层

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

2.第一个Mybatis程序

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

2.1 搭建环境

1.创建数据库

2.新建项目

  1. 新建一个普通Maven项目
  2. 删除src项目
  3. 导入Maven依赖:mybatis、mysql、junit (pom.xml)

2.2 创建一个项目

1.编写Mybatis的核心配置文件(Mybatis-config.xml)

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <!--父工程-->
    <groupId>org.example</groupId>
    <artifactId>Mybatis_Study2</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>Mybatis-01</module>
    </modules>

    <dependencies>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</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>
        </dependency>
    </dependencies>
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

</project>

2.编写Mybatis工具类(MybatisUtils)

package com.cyl.utils;

import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

// SqlSessionFactory --> SqlSession
public class MybatisUtils {

    private static SqlSessionFactory sqlSessionFactory;
    static {

        try {
            // 获取SqlSessionFactory对象
            String resources = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resources);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //既然有了SqlSessionFactory,顾名思义,就可以从中获得SqlSession的实例了
    // SqlSession完全包含了面向数据库执行Sql命令所需的所有方法
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }

}

2.3 编写代码

1.创建实体类

package com.cyl.pojo;

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

    public User() {
    }

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

    
}

2.编写Mapper接口(UserMapper)

package com.cyl.dao;

import com.cyl.pojo.User;

import java.util.List;

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

3.编写Mapper.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">
<!--namespace=绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.cyl.dao.UserDao">

    <!--id:dao/mapper的函数名
        resultType/resultMap:返回类型/集合:-->
    <!--查询语句-->
    <select id="getUserList" resultType="com.cyl.pojo.User">
        select * from mybatis.user
    </select>
</mapper>

2.4 测试

注意点:org.apache.ibatis.binding.BindingException: Type interface com.cyl.dao.UserDao is not known to the MapperRegistry.

解决方法: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>false</filtering>
            </resource>
        </resources>
    </build>

1 字节的 UTF-8 序列的字节 1 无效。

解决办法:File-->settings-->Editor-->File Encodings

package com.cyl.dao;

import com.cyl.pojo.User;
import com.cyl.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class UserDaoTest {

    @Test
    public void test(){

        // 第一步:获得SqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        // 执行SQL
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = userMapper.getUserList();

        for (User user : userList) {
            System.out.println(user);
        }

        // 关闭SqlSession
        sqlSession.close();
    }
}

3.CRUD

3.1 namespace

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

3.2 select

选择,查询语句:

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

1.编写接口

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

2.编写Mapper中的sql语句

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

3.测试

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

        sqlSession.close();

    }

3.3 Insert

3.4 update

3.5 delete

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

sqlSession.commit();

3.6 Map

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

    // Map
    int addUser2(Map<String, Object> map);
    <!--对象中的属性,可以直接取出来 传递map的key
    -->
    <insert id="addUser2" parameterType="map">
        insert into mybatis.user (id, pwd) values (#{userId},#{password})
    </insert>
    @Test
    public void addUser2(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        HashMap<String, Object> map = new HashMap<>();
        map.put("userId",5);
        map.put("userName", "Hello");
        map.put("password", "213131");

        int res = mapper.addUser2(map);

        if (res > 0){
            System.out.println("插入成功!");
        }
        // 提交事务
        sqlSession.commit();
        sqlSession.close();
    }

Map传递参数,直接在SQL中取出key即可【parameterType="map"】

对象传递参数,直接在SQL中取对象的属性即可【parameterType="Object"】

只有一个基本类型参数的情况下,可以直接在sql中取到!

多个参数用Map,或者注解

3.7 模糊查询

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

List<User> userLike = mapper.getUserLike("%李%");

2.在sql拼接中使用通配符!

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

4.配置解析

4.1 核心配置文件

mybatis-config.xml

4.2 环境配置(environments)

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

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

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

4.3 属性(properties)

可以通过properties属性来实现引用配合文件

db.properties

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

在核心配置文件中映入

    <!--引入外部配置文件-->
    <properties resource="db.properties">
        <property name="username" value="root"/>
        <property name="password" value=""/>
    </properties>
  • 可以直接引入外部文件
  • 可以在其中增加一些属性配置
  • 如果两个文件有同一个字段,优先使用外部配置文件的!

4.4 别名(typeAliases)

  • 类型别名是为java类型设置一个短的名字
  • 存在的意义仅在于用来减少类完全限定名的冗余
    <!--可以给实体类起别名-->
    <typeAliases>
        <typeAlias type="com.cyl.pojo.User" alias="User"/>
    </typeAliases>

也可以指定一个包名,Mybatis会在包名下面搜索需要的java Bean,比如:扫描实体类的包,它的默认别名就为这个类的类名,首字母小写!

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

在实体类比较少时,使用第一种方式,如果实体类十分多,建议使用第二种

4.5 设置(Settings)

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

4.6 其他配置

4.7 映射器(Mapper)

方式一:

    <!--每一个Mapper.xml都需要在Mybatis核心配置文件中注册-->
    <mappers>
        <mapper resource="com/cyl/dao/UserMapper.xml"/>
    </mappers>

方式二:使用class文件绑定注册

<!--每一个Mapper.xml都需要在Mybatis核心配置文件中注册-->
    <mappers>
<!--        <mapper resource="com/cyl/dao/UserMapper.xml"/>-->
        <mapper class="com.cyl.dao.UserMapper"/>
    </mappers>

注意点:

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

方式三:使用扫描包进行注入绑定

<!--每一个Mapper.xml都需要在Mybatis核心配置文件中注册-->
    <mappers>
<!--        <mapper resource="com/cyl/dao/UserMapper.xml"/>-->
<!--        <mapper class="com.cyl.dao.UserMapper"/>-->
        <package name="com.cyl.dao"/>
    </mappers>

注意点:

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

4.8 生命周期和作用域

开始-->SqlSessionFactoryBuilder(<--mybatis-config.xml配置文件)-->SqlSessionFactory-->SqlSession(多个)-->SQL Mapper(多个)(每一个Mapper代表一个具体的业务)-->结束

SqlSessionFactoryBuilder:

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

SqlSessionFactory:

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

SqlSession:

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

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

数据库属性字段与类属性不一致

解决方法:

  • 起别名
    <select id="getUserById" parameterType="int" resultType="com.cyl.pojo.User">
        select id,name,pwd as password from mybatis.user where id = #{id}
    </select>
  • 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" parameterType="int" resultMap="UserMap">
        select * from mybatis.user where id = #{id}
    </select>
  • resultMap 元素是Mybatis中最重要最强大的元素
  • ResultMap的设计思想是,对于简单的语句根本不需要配置显示的结果映射,而对于复杂一点的语句只需要描述它们的关系就行
  • ResultMap最优秀的地方在于,虽然已经对它相当了解了,但根本不需要显示的用到它们

6.日志

6.1 日志工厂

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

  • SJF4J
  • LOG4J

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

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

 6.2 LOG4J

什么是Log4j?

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

1.先导入log4j的包

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

2.log4j配置文件

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/cyl.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="STDOUT_LOGGING"/>
    </settings>

4. 测试

简单使用

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

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

static Logger logger = Logger.getLogger(UserDaoTest.class);

3.日志级别

        logger.info("info:进入了testLog4j");
        logger.debug("debug:进入了testLog4j");
        logger.error("error:进入了testLog4j");

7.分页

7.1 分页

使用limit分页

select * from user limit startIndex, pageSize;

使用Mybatis实现分页:

1.接口

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

2.Mapper.xml

    <select id="getUserByLimit" resultMap="UserMap" parameterType="map">
        select * from mybatis.user limit #{startIndex},#{pageSize}
    </select>

3.测试

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

        sqlSession.close();
    }

7.2 RowBounds分页

1.接口

// RowBounds
List<User> getUserByRowBounds(Map<String, Integer> map);

2.Mapper.xml

    <select id="getUserByRowBounds" resultMap="UserMap">
        select * from mybatis.user
    </select>

3.测试

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

        // RowBounds实现
        RowBounds rowBounds = new RowBounds(1, 2);

        // 通过Java代码层面实现分页
        List<User> userList = sqlSession.selectList("com.cyl.dao.UserMapper.getUserByRowBounds",null,rowBounds);

        for (User user : userList) {
            System.out.println(user);
        }

        sqlSession.close();
    }

7.3 PageHelper 分页插件

8.使用注解开发

1.注解直接在接口上实现

    @Select("select * from user")
    List<User> getUsers();

2.需要在核心配置文件中绑定接口

    <!--绑定接口-->
    <mappers>
        <mapper class="com.cyl.dao.UserMapper"/>
    </mappers>

3.测试

本质:反射机制实现

底层:动态代理

Mybatis详细实现流程:

Resources获取加载全局配置文件---->实例化SQlSessionFactoryBuilder构造器----->解析配置文件流XMLConfigBuilder----->Configuration所有配置信息----->SqlSessionFactory实例化------>transanction事务管理----->executor执行器----->创建SqlSession------>实现CRUD----->查看是否提交成功---->提交事务----->关闭

CRUD

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

    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession(true);
    }

编写接口,增加注解

package com.cyl.dao;

import com.cyl.pojo.User;
import org.apache.ibatis.annotations.*;

import java.util.List;
import java.util.Map;

public interface UserMapper {
    @Select("select * from user")
    List<User> getUsers();

    // 方法存在多个参数,参数之前必须加注解@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()中设定的属性名

#{}可以防止SQL注入,而${}不能

9.Lombok

1.在IDEA中安装Lombok插件

2.在项目中导入Lombok的jar包

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.24</version>
</dependency>

3.注解

@Data无参构造、get、set、toString、hashcode、equals
@AllArgsConstructor
@NoArgsConstructor

10. 多对一处理

创建数据库

10.1 测试环境搭建

1.导入Lombok

2.新建实体类Teacher,Student

package com.cyl.pojo;

import lombok.Data;

@Data
public class Student {
    private int id;
    private String name;

    //学生需要关联一个老师
    // 相当于属性名为teacher,类型是Teacher 数据表中属性列是tid,类型是int
    // 所以通过ResultMap映射,并且类型是对象所以是复杂结果
    private Teacher teacher;
}
package com.cyl.pojo;

import lombok.Data;

@Data
public class Teacher {
    private int id;
    private String name;
}

3.建立Mapper接口

4.建立Mapper.xml文件

5.在核心配置文件中绑定注册我们的Mapper

6.测试查询

10.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" javaType="Teacher" column="tid" select="getTeacher"/>
    </resultMap>
    <select id="getTeacher" resultType="Teacher">
        select * from teacher where id = #{id}
    </select>

10.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="id"/>
        <result property="name" column="name"/>
        <association property="teacher" javaType="Teacher">
            <result property="name" column="tname"/>
        </association>
    </resultMap>

回顾MySQL查询方式:

  • 子查询
  • 联表查询

11. 一对多处理

1.导入Lombok

2.新建实体类Teacher,Student、

package com.cyl.pojo;

import lombok.Data;

import java.util.List;

@Data
public class Teacher {
    private int id;
    private String name;

    // 一个老师拥有多个学生
    private List<Student> students;
}
package com.cyl.pojo;

import lombok.Data;

@Data
public class Student {
    private int id;
    private String name;
    private int tid;
}

3.建立Mapper接口

4.建立Mapper.xml文件

5.在核心配置文件中绑定注册我们的Mapper

6.测试查询

11.2 按结果嵌套处理

<!--按结果嵌套查询-->
    <select id="getTeacherAndStudent" resultMap="TeacherStudent">
        select t.id tid, t.name tname, s.id sid, s.name sname
        from teacher t,student s
        where t.id = s.tid and t.id = #{tid}
    </select>

    <resultMap id="TeacherStudent" type="Teacher">
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>
        <!--
            复杂的属性:需要单独处理
            对象:association   集合:collection
            对象/集合的java属性类型:javaType
            集合中的泛指信息(List/Set等),使用ofType获取
        -->
        <collection property="students" ofType="Student">
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
            <result property="tid" column="tid"/>
        </collection>
    </resultMap>

11.3 按查询嵌套处理

<!--按查询嵌套处理-->
    <select id="getTeacherAndStudent2" resultMap="StudentTeacher2">
        select * from teacher where id = #{tid}
    </select>
    <resultMap id="StudentTeacher2" type="Teacher">
        <collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/>
    </resultMap>

    <select id="getStudentByTeacherId" resultType="Student">
        select * from student where tid = #{tid}
    </select>

小结

1.关联-association【多对一】

2.集合-collection【一对多】

3.javaType & ofType

  1. javaType 用来指定实体类中属性的类型
  2. ofType 用来指定映射到List或者集合中的pojo类型,泛型中的约束类型

12.动态SQL

指根据不同的条件生成不同的SQL语句

12.1 搭建环境

创建基础工程

1.导包

2.编写配置文件

3.编写实体类

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

12.2 IF

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

12.3 trim,where,set

<where></where>相当于where 1=1;即需要and自动拼接and,不需要and自动去掉and

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

12.4 choose,when,otherwise

    <select id="queryBlogChoose" parameterType="map" resultType="Blog">
        select * from 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>

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

12.4 SQL片段

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

    <sql id="if-title-author">
        <if test="title != null">
            and title = #{title}
        </if>
        <if test="author != null">
            and author = #{author}
        </if>
    </sql>

2.在需要使用的地方使用include标签引用即可

    <select id="queryBlogIf" parameterType="map" resultType="Blog">
        select * from blog
        <where>
            <include refid="if-title-author"></include>
        </where>
    </select>

注意:

  • 最好基于单表来定义SQL片段
  • 不要存在where标签

12.5 Foreach

select * from user where 1=1 and

    <foreach item="id" collection="ids"
        open="(" separator="or" close=")">
            #{id}
    </foreach>


(id=1 or id=2 or id=3)
    <!--select * from blog where 1=1 and (id=1 or id=2 or id=3)

    传递一个map,这map中可以存在一个集合!
    -->
    <select id="queryBlogForeach" parameterType="map" resultType="Blog">
        select * from blog
        <where>
            <foreach collection="ids" item="id" open="and (" close=")" separator="or">
                id = #{id}
            </foreach>
        </where>
    </select>

动态SQL就是在拼接SQL语句,只要保证SQL的正确性,按照SQL的格式,排列组合即可

13 缓存

什么样的数据经常使用缓存?经常查询且不常改变的数据

13.1 一级缓存

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

  • 与数据库同一会话期间查询到的数据会放在本地缓存中
  • 以后如果需要获取相同的数据,直接从缓存中拿,没必要再查询数据库

测试步骤:

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

缓存失效情况:

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

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

一级缓存相当于一个Mapper

13.2 二级缓存

二级缓存也叫全局缓存

基于namespace级别的缓存,一个命名空间,对应一个二级缓存

工作机制

  • 一个会话查询一条数据,这个数据会被放在当前会话的一级缓存中
  • 如果当前会话关闭了,这个会话对应的一级缓存就没了;但会话关闭了,一级缓存中的数据被保存到二级缓存中;
  • 新的会话查询信息,可以从二级缓存中获取内容
  • 不同的mapper查出的数据会放在自己对应的缓存(map)中

步骤:

1.开启全局缓存

<setting name="cacheEnabled" value="true"/>

2.在要使用二级缓存的Mapper中开启

<cache
        eviction="FIFO"
        flushInterval="60000"
        size="512"
        readOnly="true"/>

3.测试

小结:

  • 只要开启了二级缓存,在同一个Mapper下就有效
  • 所有的数据都会先放在一级缓存中
  • 只有当会话提交或关闭的时候,才会提交到二级缓存中!

13.3.缓存原理

缓存顺序:

1.先看二级缓存中有没有

2.再看一级缓存中有没有

3.查询数据库

13.4 Ehcache

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值