Mybatis-实习期笔记

Mybatis

配置

全局配置文件中,各个标签要按照如下顺序进行配置,因为mybatis加载配置文件的源码中是按照这个顺序进行解析的

<configuration>
	<!-- 配置顺序如下
     properties  

     settings

     typeAliases

     typeHandlers

     objectFactory

     plugins

     environments
        environment
            transactionManager
            dataSource

     mappers
     -->
</configuration>

属性(properties)

这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。

<properties resource="org/mybatis/example/config.properties">
  <property name="username" value="dev_user"/>
  <property name="password" value="F2Fa3!33TYyg"/>
</properties>

设置好的属性可以在整个配置文件中用来替换需要动态配置的属性值。

<dataSource type="POOLED">
  <property name="driver" value="${driver}"/>  //来自于配置文件
  <property name="url" value="${url}"/>			
  <property name="username" value="${username}"/> // 来自于properties子元素
  <property name="password" value="${password}"/>
</dataSource>

优先级:参数传递 > resource配置文件 > properties元素中指定属性

设置(settings)

用来开启或关闭mybatis的一些特性,比如可以用<setting name="lazyLoadingEnabled" value="true"/>来开启延迟加载,可以用<settings name="cacheEnabled" value="true"/>来开启二级缓存。详细在下文。

类型别名(typeAliases)

别名可以降低冗余的全限定类名的书写

<typeAliases>
  <typeAlias alias="Author" type="domain.blog.Author"/>
</typeAliases>

也可以指定包名,Mybatis会在包名下搜索需要的java bean,此时(没有注解的情况下)会使用Bean的首字母小写来作为它的别名,如domain.blog.Author —> author

<typeAliases>
  <package name="domain.blog"/>
</typeAliases>

另外,对于基本的Java类型 -> 8大基本类型以及包装类,以及String类型,mybatis提供了默认的别名,别名为其简单类名的小写,比如原本需要写java.lang.String,其实可以简写为string

类型处理器(typeHandlers)

用于处理Java类型和Jdbc类型之间的转换,mybatis有许多内置的TypeHandler,比如StringTypeHandler,会处理Java类型String和Jdbc类型CHAR和VARCHAR。这个标签用的不多

对象工厂(objectFactory)

每次 MyBatis 创建结果对象的新实例时,它都会使用一个对象工厂(ObjectFactory)实例来完成实例化工作。 默认的对象工厂需要做的仅仅是实例化目标类,要么通过默认无参构造方法,要么通过存在的参数映射来调用带有参数的构造方法。 如果想覆盖对象工厂的默认行为,可以通过创建自己的对象工厂来实现。

插件(plugins)

MyBatis 允许你在映射语句执行过程中的某一点进行拦截调用。可以用来配置mybatis的插件,比如在开发中经常需要对查询结果进行分页,就需要用到pageHelper分页插件,这些插件就是通过这个标签进行配置的。在mybatis底层,运用了责任链模式+动态代理去实现插件的功能

环境配置(environments)

MyBatis 可以配置成适应多种环境,这种机制有助于将 SQL 映射应用于多种数据库之中, 现实情况下有多种理由需要这么做。例如,开发、测试和生产环境需要有不同的配置;或者想在具有相同 Schema 的多个生产数据库中使用相同的 SQL 映射。还有许多类似的使用场景。

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

所以,如果你想连接两个数据库,就需要创建两个 SqlSessionFactory 实例,每个数据库对应一个。而如果是三个数据库,就需要三个实例,依此类推,记起来很简单:

  • 每个数据库对应一个 SqlSessionFactory 实例

为了指定创建哪种环境,只要将它作为可选的参数传递给 SqlSessionFactoryBuilder 即可。可以接受环境配置的两个方法签名是:

SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader, environment);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader, environment, properties);

数据库厂商标识(databaseIdProvider)

映射器(mappers)

既然 MyBatis 的行为已经由上述元素配置完了,我们现在就要来定义 SQL 映射语句了。 但首先,我们需要告诉 MyBatis 到哪里去找到这些语句。 在自动查找资源方面,Java 并没有提供一个很好的解决方案,所以最好的办法是直接告诉 MyBatis 到哪里去找映射文件。 你可以使用相对于类路径的资源引用,或完全限定资源定位符(包括 file:/// 形式的 URL),或类名和包名等。例如:

<!-- 使用相对于类路径的资源引用 -->
<mappers>
  <mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
  <mapper resource="org/mybatis/builder/BlogMapper.xml"/>
  <mapper resource="org/mybatis/builder/PostMapper.xml"/>
</mappers>
<!-- 使用完全限定资源定位符(URL) -->
<mappers>
  <mapper url="file:///var/mappers/AuthorMapper.xml"/>
  <mapper url="file:///var/mappers/BlogMapper.xml"/>
  <mapper url="file:///var/mappers/PostMapper.xml"/>
</mappers>
<!-- 使用映射器接口实现类的完全限定类名 -->
<mappers>
  <mapper class="org.mybatis.builder.AuthorMapper"/>
  <mapper class="org.mybatis.builder.BlogMapper"/>
  <mapper class="org.mybatis.builder.PostMapper"/>
</mappers>
<!-- 将包内的映射器接口实现全部注册为映射器 -->
<mappers>
  <package name="org.mybatis.builder"/>
</mappers>

Mybatis框架Demo笔记

不使用其他框架进行整合,单纯使用maven创建项目来整理和测试Mybatis的配置和功能点,还原最基本的Mybatis配置和使用。

基本步骤:

使用mybatis基本过程:

  1. 编写全局配置文件mybatis-config.xml
  2. 编写mapper映射文件
  3. 加载全局配置文件,生成SqlSessionFactory
  4. 创建SqlSession,调用mapper映射文件中的SQL语句来执行CRUD操作
1.导入依赖包
<dependencies>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.17</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.6</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.12</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.10</version>
        <scope>test</scope>
    </dependency>
</dependencies>
2.编写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">

<mapper namespace="com.puremybatis.mapper.StudentMapper">
    <select id="findAllStudent" resultType="com.puremybatis.domain.Student">
        SELECT * FROM student;
    </select>

    <insert id="insert" parameterType="com.puremybatis.domain.Student">
        INSERT INTO student VALUES (#{Sno},#{Sname},#{Ssex},#{Sclass},#{SBirthday})
    </insert>

    <delete id="delete" parameterType="int">
        DELETE FROM student WHERE Sno = #{sno};
    </delete>

    <update id="update" parameterType="com.puremybatis.domain.Student">
        UPDATE student SET Sname = #{Sname},SClass = #{Sclass},Ssex = #{Ssex},Sbirthday = #{Sbirthday} WHERE Sno = #{Sno}
    </update>
</mapper>
3.dao业务执行
public class StudentDao {

    private SqlSessionFactory sqlSessionFactory;

    public StudentDao(String configPath) throws IOException {
        // 1.加载配置文件
        InputStream inputStream = Resources.getResourceAsStream(configPath);
        // 2.建造者模式获取工厂
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }
	// 查
    public List<Student> findAllStudent() {
        // 3.从工厂获得SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 4.SqlSession调用mapper映射文件中的SQL语句来执行CRUD操作
        List<Student> studentList = sqlSession.selectList("findAllStudent");
        // 5.关闭连接
        sqlSession.close();
        return studentList;
    }
	// 增
    public void insert(Student student) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        sqlSession.insert("insert",student);
        // 6.涉及编辑操作的需要提交
        sqlSession.commit();
        sqlSession.close();
    }
    // ...
}
4.测试
@Before
public void init() throws IOException {
    // 将配置文件路径给dao
    String path = "mybatis-config.xml";
    studentDao = new StudentDao(path);
}

@Test
public void testForFind() {
    List<Student> all = studentDao.findAllStudent();
    all.forEach(System.out::println);
}
// 其余demo中体现,此处省略

基于Mapper代理

mapper接口和mapper.xml之间需要遵循一定规则,才能成功的让mybatis将mapper接口和mapper.xml绑定起来

  1. mapper接口的全限定名,要和mapper.xml的namespace属性一致
  2. mapper接口中的方法名要和mapper.xml中的SQL标签的id一致
  3. mapper接口中的方法入参类型,要和mapper.xml中SQL语句的入参类型一致
  4. mapper接口中的方法出参类型,要和mapper.xml中SQL语句的返回值类型一致

image-20220208174250142

public interface StudentMapper {
    public List<Student> findAllStudent();
    public void insert(Student student);
    public void delete(Integer id);
    public void update(Student student);
    public Student findStudentBySno(Integer sno);
}
public class MapperMybatisTest {
	// 工厂
    private SqlSessionFactory sqlSessionFactory;

    @Before
    public void init() throws IOException {
        // 获得和加载配置文件
        InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
    }
    
    @Test
    public void testForSelectOne() {
        // 获得SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
        Student student = studentMapper.findStudentBySno(1);
        System.out.println(student.toString());
    }
}

基于注解

以下效果同XML映射文件,但是如果是复杂语句基本就不能用了

/**
 * 使用注解形式
 * @return 返回所有学生信息
 */
@Select("SELECT * FROM T_STUDENT")
@Results(id = "StudentMapAno",value = {
    @Result(column = "STUDENT_NO",property = "sno"),
    @Result(column = "STUDENT_NAME",property = "studentName"),
    @Result(column = "STUDENT_SEX",property = "studentSex"),
    @Result(column = "CLASS_NO",property = "studentClass"),
    @Result(column = "STUDENT_BIRTHDAY",property = "studentBirthday"),
})
List<Student> findAllStudentAno();

关于缓存

一级缓存:

在中间不进行数据修改操作的情况下对相同的数据进行查询

@Test
public void testForSelectOne() {
    // 使用相同的sqlSession
    SqlSession sqlSession = sqlSessionFactory.openSession();
    StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
    // 第1次查询sno为1的同学
    Student student = studentMapper.findStudentBySno(1);
    System.out.println(student.toString());
	// 进行了第2次查询sno为1的同学
    Student student2 = studentMapper.findStudentBySno(1);
    System.out.println(student2.toString());
}

image-20220208161538177

如果中间进行了数据变更

@Test
// 测试在进行更新操作后的查询情况
public void test2() {
    SqlSession sqlSession = sqlSessionFactory.openSession();
    StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
    Student student = studentMapper.findStudentBySno(1);
    System.out.println(student.toString());

    // 在相同查询过程进行一次编辑的操作
    Student student2 = new Student();
    student2.setSno(4);
    student2.setSname("李三");
    student2.setSsex("女");
    student2.setSclass("3");
    student2.setSbirthday("2021-07-12");
    studentMapper.update(student2);

    Student student3 = studentMapper.findStudentBySno(1);
    System.out.println(student3.toString());
}

image-20220208162843521

总结:

  1. 一级缓存默认为开启的
  2. 一级缓存只对同一个SqlSession有效
  3. 一级缓存在数据更新时被清除
  4. 配置了flushCache=true属性会清楚缓存
二级缓存

开启二级缓存:

  1. 全局配置文件mybatis-config.xml

    <settings>
        <setting name="cacheEnabled" value="true" />
    </settings>
    
  2. 映射文件

    <cache/>
    
  3. 对应实体类要实现Serializable

    public class Student implements Serializable {...}
    

关于resultType和resultMap

resultType:当使用resultType做SQL语句返回结果类型处理时,对于SQL语句查询出的字段在相应的pojo中必须有和它相同的字段对应,而resultType中的内容就是pojo在本项目中的位置。

resultMap:当使用resultMap做SQL语句返回结果类型处理时,通常需要在mapper.xml中定义resultMap进行pojo和相应表字段的对应。(多用于复杂的映射关系)

<resultMap type="Score" id="ScoreMap">
    <id column="SCORE_ID"  property="scoreId"/>
    <result column="COURSE_NO" property="courseNo"/>
    <result column="STUDENT_NO" property="sno"/>
    <result column="SCORE" property="score"/>
    <result column="VALID" property="valid"/>
</resultMap>
<!--这里的Score由别名代替了全限定类名-->
<select id="findAllScore" resultMap="ScoreMap" resultType="Score">
    SELECT * FROM T_SCORE
</select>

动态SQL

img

简单demo

If:
单条件
<select id="findScoreLarger" parameterType="int" resultMap="ScoreMap">
    SELECT * FROM T_SCORE
    <if test="value != null">
        WHERE SCORE>#{value}
    </if>
</select>
// 有数值时,查询大于等于该数值成绩的成绩 SELECT * FROM T_SCORE WHERE SCORE>?
List<Score> list = scoreMapper.findScoreLarger(90);
// 空值时,查询所有成绩 SELECT * FROM T_SCORE
List<Score> list2 = scoreMapper.findScoreLarger(null);
choose、when、otherwise:
多条件分支
<select id="findScoreLike" parameterType="Score" resultType="Score" resultMap="ScoreMap">
    SELECT * FROM T_SCORE WHERE SCORE IS NOT NULL
    <choose>
        <when test = "sno != null">
            AND STUDENT_NO = #{sno}
        </when>
        <when test = "courseNo != null">
            AND COURSE_NO = #{courseNo}
        </when>
        <otherwise>
        </otherwise>
    </choose>
</select>
List<Score> list = scoreMapper.findScoreLike(score);
logger.info("精准查询某位学生某科的成绩单");
list.forEach(logger::info);

// 学号置空
score.setSno(null);
List<Score> scoresNoSno = scoreMapper.findScoreLike(score);
logger.info("模糊查询某科的成绩单");
scoresNoSno.forEach(logger::info);

// 学科置空
score.setCourseNo(null);
List<Score> listNoAll = scoreMapper.findScoreLike(score);
logger.info("模糊查询某科的成绩单");
listNoAll.forEach(logger::info);

trim、where、set:
解决拼接的问题
  • where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
<select id="findScoreLargerValid" parameterType="Score" resultType="Score" resultMap="ScoreMap">
    SELECT * FROM T_SCORE
    <where>
        <if test = "valid != null">
            VALID = #{valid}
        </if>
        <if test="score != null">
            AND SCORE > #{score}
        </if>
    </where>
</select>

image-20220210105323887

  • trim,prefixOverridessuffixOverrides)属性会忽略通过管道符分隔的文本序列(注意此例中的空格是必要的)。上述例子会移除所有 prefixOverridessuffixOverrides)属性中指定的内容,并且插入 prefix (suffix)属性中指定的内容。

示例1.同上WHERE语句效果

<select id="findScoreLargerTrim" parameterType="Score" resultType="Score" resultMap="ScoreMap">
    SELECT * FROM T_SCORE
    <!--前缀WHERE,AND和OR在不合适的时候会被切割,注意空格-->
    <trim prefix="WHERE" prefixOverrides="AND |OR ">
        <if test = "valid != null">
            VALID = #{valid}
        </if>
        <!--如果上面没有内容,这里的AND会被切割掉-->
        <if test="score != null">
            AND SCORE > #{score}
        </if>
    </trim>
</select>

示例2.改善插入语句,有输入的值才进行插入,动态SQL语句过滤空值

<insert id="insertWithIf" parameterType="Student">
    INSERT INTO T_STUDENT
    <trim prefix="(" suffix=")" suffixOverrides=",">
        <if test="sno != null">
            STUDENT_NO,
        </if>
        <if test="studentName != null">
            STUDENT_NAME,
        </if>
        <if test="studentClass != null">
            CLASS_NO,
        </if>
        <if test="studentSex != null">
            STUDENT_SEX,
        </if>
        <if test="studentBirthday != null">
            STUDENT_SEX,
        </if>
    </trim>
    <trim prefix="VALUES(" suffix=")" suffixOverrides=",">
        <if test="sno != null">
            #{sno},
        </if>
        <if test="studentName != null">
            #{studentName},
        </if>
        <if test="studentClass != null">
            #{studentClass},
        </if>
        <if test="studentSex != null">
            #{studentSex},
        </if>
        <if test="studentBirthday != null">
            #{studentBirthday},
        </if>
    </trim>
</insert>

image-20220210111403803

foreach
<select id="selectPostIn" resultType="domain.blog.Post">
  SELECT *
  FROM POST P
  <where>
    <foreach item="item" index="index" collection="list"
        open="ID in (" separator="," close=")" nullable="true">
          #{item}
    </foreach>
  </where>
</select>

foreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头与结尾的字符串以及集合项迭代之间的分隔符。这个元素也不会错误地添加多余的分隔符。

提示 你可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象作为集合参数传递给 foreach。当使用可迭代对象或者数组时,index 是当前迭代的序号,item 的值是本次迭代获取到的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。

<select id="selectEnum" resultType="Score" resultMap="ScoreMap">
    SELECT * FROM T_SCORE
    <where>
        <foreach collection="array" open="STUDENT_NO IN (" separator="," close=")" index="index" item="item">
            #{item}
        </foreach>
    </where>
</select>
int[] snoList = {1,2};
// 输入一个数组
List<Score> list = scoreMapper.selectEnum(snoList);

image-20220210114253017

分页

分页插件PageHelper

文档:https://pagehelper.github.io/docs/howtouse/

  1. 导入依赖

    <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper</artifactId>
        <version>5.1.8</version>
    </dependency>
    
  2. 全局配置文件

    <!--mybatis框架的配置方法,spring另外-->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
            <!--具体配置参考文档,太多不列了-->
            <property name="helperDialect" value="mysql"/>
        </plugin>
    </plugins>
    
  3. 使用

    @Test
    // 方法一:静态方法PageHelper.startPage
    public void testPage() {
        ...
    	// 两个参数分别是页码和页面大小
        PageHelper.startPage(3,2);
        // startPage后的第一个Sql语句会被分页处理
        // 这里不一定要Page,List也行,但是一定要是Page(强制转换成Page)才能取出分页的具体信息(如页码,页大小等)
        Page<Score> scorePage1 = scoreMapper.findAllScorePage();
        Page<Score> scorePage2 = scoreMapper.findAllScorePage();
        // 打印省略
    }
    

    image-20220210152519088

    @Test
    // 方法二:接口传入RowBounds
    /**
     * RowBounds方式调用
     * @param rowBounds RowBounds
     * @return 全部成绩单page
    */
    List<Score> findAllScoreRowBounds(RowBounds rowBounds);
    
    public void testPageRowBounds() {
    	...
        // offset:起点,如此处为第六行数据,limit:同pageSize为页大小
        // 可以在配置文件设置offsetAsPageNum:true来将offset更改为pageSize
        List<Score> list = scoreMapper.findAllScoreRowBounds(new RowBounds(5,4));
        list.forEach(logger::info);
        
        // RowBounds的子类PageRowBounds,提供了获取查询总数的属性
        PageRowBounds prb = new PageRowBounds(5,4);
        List<Score> list2 = scoreMapper.findAllScoreRowBounds(prb);
        logger.info("查询总数" + prb.getTotal());
    }
    

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-WitpVZHQ-1645602724504)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20220210155222425.png)]

获取页面信息方式补充
PageInfo page =  new PageInfo(list);

image-20220210160759431

PageHelper.startPage方法重要提示
  • 只有紧跟在PageHelper.startPage方法后的第一个Mybatis的**查询(Select)**方法会被分页。

  • 请不要配置多个分页插件

请不要在系统中配置多个分页插件(使用Spring时,mybatis-config.xmlSpring<bean>配置方式,请选择其中一种,不要同时配置多个分页插件)!

  • 分页插件不支持带有for update语句的分页

对于带有for update的sql,会抛出运行时异常,对于这样的sql建议手动分页,毕竟这样的sql需要重视。

  • 分页插件不支持嵌套结果映射

由于嵌套结果方式会导致结果集被折叠,因此分页查询的结果在折叠后总数会减少,所以无法保证分页结果数量正确。

问题和解决:

1.关于maven不打包xml

image-20220208142348088

解决:

pom.xml中,使这些文件不会被过滤

<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>

2.插入中文出现问号

image-20220208140924742

解决:

jdbc.url=jdbc:mysql://localhost:3306/demo?characterEncoding=utf8

3.mybatis如果配置中文注释导致报错

image-20220208153540852

解决:

目前就是直接删掉中文注释

4.二级缓存不生效

以下代码无法使用二级缓存

@Test
// 使用不同的sqlSession测试二级缓存
public void test3() {
    SqlSession sqlSession = sqlSessionFactory.openSession();
    SqlSession sqlSession2 = sqlSessionFactory.openSession();

    StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
    // 使用Sno查找学生
    Student student = studentMapper.findStudentBySno(1);
    System.out.println(student.toString());

    StudentMapper studentMapper2 = sqlSession2.getMapper(StudentMapper.class);
    // 第二个sqlSession查找同一个学生
    Student student2 = studentMapper2.findStudentBySno(1);
    System.out.println(student2.toString());

    sqlSession.close();
    sqlSession2.close();
}

解决:

二级缓存失效原因:

1.sqlSession没有进行提交

image-20220209094043282

提交后,正常命中缓存

image-20220209091703426

2.进行了数据修改的情况下

和一级缓存一样,避免读取脏数据,更新数据后清除了缓存

image-20220209095022007

配置解析(参考和了解)

基本步骤:获取连接,封装参数,执行

String resource = "mybatis-config.xml";
//1.读取resources下面的mybatis-config.xml文件
InputStream inputStream = Resources.getResourceAsStream(resource);
//2.使用SqlSessionFactoryBuilder创建SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//3.通过sqlSessionFactory创建SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();

1.Resources读取配置文件

主要是通过ClassLoader.getResourceAsStream()方法获取指定的classpath路径下的Resource 。

public static InputStream getResourceAsStream(String resource) throws IOException {
	return getResourceAsStream(null, resource);
} 
//loader赋值为null
public static InputStream getResourceAsStream(ClassLoader loader, String resource) throws IOException {
	InputStream in = classLoaderWrapper.getResourceAsStream(resource, loader);
	if (in == null) {
		throw new IOException("Could not find resource " + resource);
	} 
	return in;
}
//classLoader为null
public InputStream getResourceAsStream(String resource, ClassLoader classLoader) {
	return getResourceAsStream(resource, getClassLoaders(classLoader));
} 
//classLoader类加载
InputStream getResourceAsStream(String resource, ClassLoader[] classLoader) {
	for (ClassLoader cl : classLoader) {
		if (null != cl) {
			//加载指定路径文件流
			InputStream returnValue = cl.getResourceAsStream(resource);
			// now, some class loaders want this leading "/", so we'll add it and try again if we didn't find the resource
			if (null == returnValue) {
				returnValue = cl.getResourceAsStream("/" + resource);
			} 
			if (null != returnValue) {
				return returnValue;
			}
		}
	} 
	return null;
}

2.通过SqlSessionFactoryBuilder创建SqlSessionFactory

//SqlSessionFactoryBuilder是一个建造者模式
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
public SqlSessionFactory build(InputStream inputStream) {
	return build(inputStream, null, null);
}
//XMLConfigBuilder也是建造者模式
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
	try {
		XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
		return build(parser.parse());
	} catch (Exception e) {
		throw ExceptionFactory.wrapException("Error building SqlSession.", e);
	} finally {
		ErrorContext.instance().reset();
		try {
			inputStream.close();
		} catch (IOException e) {
			// Intentionally ignore. Prefer previous error.
		}
	}
}
//接下来进入XMLConfigBuilder构造函数
public XMLConfigBuilder(InputStream inputStream, String environment, Properties props) {
	this(new XPathParser(inputStream, true, props, new XMLMapperEntityResolver()), environment, props);
}
//接下来进入this后,初始化Configuration
private XMLConfigBuilder(XPathParser parser, String environment, Properties props) {
	super(new Configuration());
	ErrorContext.instance().resource("SQL Mapper Configuration");
	this.configuration.setVariables(props);
	this.parsed = false;
	this.environment = environment;
	this.parser = parser;
}
//其中parser.parse()负责解析xml,build(configuration)创建SqlSessionFactory
return build(parser.parse());

3.parser.parse()解析xml文件

parseConfiguration完成的是解析configuration下的标签

public Configuration parse() {
	//判断是否重复解析
	if (parsed) {
		throw new BuilderException("Each XMLConfigBuilder can only be used once.");
	} 
	parsed = true;
	//读取配置文件一级节点configuration
	parseConfiguration(parser.evalNode("/configuration"));
	return configuration;
}

private void parseConfiguration(XNode root) {
	try {
		//properties 标签,用来配置参数信息,比如最常见的数据库连接信息
		propertiesElement(root.evalNode("properties"));
		Properties settings = settingsAsProperties(root.evalNode("settings"));
		loadCustomVfs(settings);
		loadCustomLogImpl(settings);
		//实体别名两种方式:1.指定单个实体;2.指定包
		typeAliasesElement(root.evalNode("typeAliases"));
		//插件
		pluginElement(root.evalNode("plugins"));
		//用来创建对象(数据库数据映射成java对象时)
		objectFactoryElement(root.evalNode("objectFactory"));
		objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
		reflectorFactoryElement(root.evalNode("reflectorFactory"));
		settingsElement(settings);
		// read it after objectFactory and objectWrapperFactory issue #631
		//数据库环境
		environmentsElement(root.evalNode("environments"));
		databaseIdProviderElement(root.evalNode("databaseIdProvider"));
		//数据库类型和Java数据类型的转换
		typeHandlerElement(root.evalNode("typeHandlers"));
		//这个是对数据库增删改查的解析
		mapperElement(root.evalNode("mappers"));
	} catch (Exception e) {
		throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
	}
}

通过解析configuration.xml文件,获取其中的Environment、Setting,重要的是将下的所有解析出来之后添加到
Configuration,Configuration类似于配置中心,所有的配置信息都在这里。

private void mapperElement(XNode parent) throws Exception {
	if (parent != null) {
			for (XNode child : parent.getChildren()) {
			//解析<package name=""/>
			if ("package".equals(child.getName())) {
				String mapperPackage = child.getStringAttribute("name");
				//包路径存到mapperRegistry中
				configuration.addMappers(mapperPackage);
			} else {
				//解析<mapper url="" class="" resource=""></mapper>
				String resource = child.getStringAttribute("resource");
				String url = child.getStringAttribute("url");
				String mapperClass = child.getStringAttribute("class");
				if (resource != null && url == null && mapperClass == null) {
					ErrorContext.instance().resource(resource);
					//读取Mapper.xml文件
					InputStream inputStream = Resources.getResourceAsStream(resource);
					XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream,
					configuration, resource, configuration.getSqlFragments());
					mapperParser.parse();
				} else if (resource == null && url != null && mapperClass == null) {
					ErrorContext.instance().resource(url);
					InputStream inputStream = Resources.getUrlAsStream(url);
					XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream,
					configuration, url, configuration.getSqlFragments());
					mapperParser.parse();
				} else if (resource == null && url == null && mapperClass != null) {
					Class<?> mapperInterface = Resources.classForName(mapperClass);
					configuration.addMapper(mapperInterface);
				} else {
					throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
				}
			}
		}
	}
}

4.mapperParser.parse()对Mapper映射器的解析

public void parse() {
	if (!configuration.isResourceLoaded(resource)) {
		//解析所有的子标签
		configurationElement(parser.evalNode("/mapper"));
		configuration.addLoadedResource(resource);
		//把namespace(接口类型)和工厂类绑定起来
		bindMapperForNamespace();
	}
	parsePendingResultMaps();
	parsePendingCacheRefs();
	parsePendingStatements();
} 
//这里面解析的是Mapper.xml的标签
private void configurationElement(XNode context) {
	try {
		String namespace = context.getStringAttribute("namespace");
		if (namespace == null || namespace.equals("")) {
			throw new BuilderException("Mapper's namespace cannot be empty");
		} 
		builderAssistant.setCurrentNamespace(namespace);
		//对其他命名空间缓存配置的引用
		cacheRefElement(context.evalNode("cache-ref"));
		//对给定命名空间的缓存配置
		cacheElement(context.evalNode("cache"));
		parameterMapElement(context.evalNodes("/mapper/parameterMap"));
		//是最复杂也是最强大的元素,用来描述如何从数据库结果集中来加载对象
		resultMapElements(context.evalNodes("/mapper/resultMap"));
		//可被其他语句引用的可重用语句块
		sqlElement(context.evalNodes("/mapper/sql"));
		//获得MappedStatement对象(增删改查标签)
		buildStatementFromContext(context.evalNodes("select|insert|update|delete"));
	} catch (Exception e) {
		throw new BuilderException("Error parsing Mapper XML. The XML location is '" + resource + "'. Cause: " + e, e);
	}
}
//获得MappedStatement对象(增删改查标签)
private void buildStatementFromContext(List<XNode> list) {
	if (configuration.getDatabaseId() != null) {
		buildStatementFromContext(list, configuration.getDatabaseId());
	} 
	buildStatementFromContext(list, null);
}
//获得MappedStatement对象(增删改查标签)
private void buildStatementFromContext(List<XNode> list, String requiredDatabaseId) {
	//循环增删改查标签
	for (XNode context : list) {
		final XMLStatementBuilder statementParser = new XMLStatementBuilder(configuration, builderAssistant, context, requiredDatabaseId);
		try {
			//解析insert/update/select/del中的标签
			statementParser.parseStatementNode();
		} catch (IncompleteElementException e) {
			configuration.addIncompleteStatement(statementParser);
		}
	}
}
public void parseStatementNode() {
	//在命名空间中唯一的标识符,可以被用来引用这条语句
	String id = context.getStringAttribute("id");
	//数据库厂商标识
	String databaseId = context.getStringAttribute("databaseId");
	if (!databaseIdMatchesCurrent(id, databaseId, this.requiredDatabaseId)) {
		return;
	} 
	String nodeName = context.getNode().getNodeName();
	SqlCommandType sqlCommandType =
	SqlCommandType.valueOf(nodeName.toUpperCase(Locale.ENGLISH));
	boolean isSelect = sqlCommandType == SqlCommandType.SELECT;
	//flushCache和useCache都和二级缓存有关
	//将其设置为true后,只要语句被调用,都会导致本地缓存和二级缓存被清空,默认值:false
	boolean flushCache = context.getBooleanAttribute("flushCache", !isSelect);
	//将其设置为 true 后,将会导致本条语句的结果被二级缓存缓存起来,默认值:对 select 元素为 true
	boolean useCache = context.getBooleanAttribute("useCache", isSelect);
	boolean resultOrdered = context.getBooleanAttribute("resultOrdered", false);
	// Include Fragments before parsing
	XMLIncludeTransformer includeParser = new XMLIncludeTransformer(configuration, builderAssistant);
	includeParser.applyIncludes(context.getNode());
	//会传入这条语句的参数类的完全限定名或别名
	String parameterType = context.getStringAttribute("parameterType");
	Class<?> parameterTypeClass = resolveClass(parameterType);
	String lang = context.getStringAttribute("lang");
	LanguageDriver langDriver = getLanguageDriver(lang);
	// Parse selectKey after includes and remove them.
	processSelectKeyNodes(id, parameterTypeClass, langDriver);
	// Parse the SQL (pre: <selectKey> and <include> were parsed and removed)
	KeyGenerator keyGenerator;
	String keyStatementId = id + SelectKeyGenerator.SELECT_KEY_SUFFIX;
	keyStatementId = builderAssistant.applyCurrentNamespace(keyStatementId, true);
	if (configuration.hasKeyGenerator(keyStatementId)) {
		keyGenerator = configuration.getKeyGenerator(keyStatementId);
	} else {
		keyGenerator = context.getBooleanAttribute("useGeneratedKeys", configuration.isUseGeneratedKeys() && SqlCommandType.INSERT.equals(sqlCommandType)) ? Jdbc3KeyGenerator.INSTANCE : NoKeyGenerator.INSTANCE;
	} 
	SqlSource sqlSource = langDriver.createSqlSource(configuration, context, parameterTypeClass);
	StatementType statementType =
	StatementType.valueOf(context.getStringAttribute("statementType",
	StatementType.PREPARED.toString()));
	Integer fetchSize = context.getIntAttribute("fetchSize");
	Integer timeout = context.getIntAttribute("timeout");
	String parameterMap = context.getStringAttribute("parameterMap");
	//从这条语句中返回的期望类型的类的完全限定名或别名
	String resultType = context.getStringAttribute("resultType");
	Class<?> resultTypeClass = resolveClass(resultType);
	//外部resultMap的命名引用
	String resultMap = context.getStringAttribute("resultMap");
	String resultSetType = context.getStringAttribute("resultSetType");
	ResultSetType resultSetTypeEnum = resolveResultSetType(resultSetType);
	String keyProperty = context.getStringAttribute("keyProperty");
	String keyColumn = context.getStringAttribute("keyColumn");
	String resultSets = context.getStringAttribute("resultSets");
	builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType,
	fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass,
	resultSetTypeEnum, flushCache, useCache, resultOrdered,
	keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets);
}
public MappedStatement addMappedStatement(
	String id,
	SqlSource sqlSource,
	StatementType statementType,
	SqlCommandType sqlCommandType,
	Integer fetchSize,
	Integer timeout,
	String parameterMap,
	Class<?> parameterType,
	String resultMap,
	Class<?> resultType,
	ResultSetType resultSetType,
	boolean flushCache,
	boolean useCache,
	boolean resultOrdered,
	KeyGenerator keyGenerator,
	String keyProperty,
	String keyColumn,
	String databaseId,
	LanguageDriver lang,
	String resultSets) {
	if (unresolvedCacheRef) {
		throw new IncompleteElementException("Cache-ref not yet resolved");
	} 
		id = applyCurrentNamespace(id, false);
		boolean isSelect = sqlCommandType == SqlCommandType.SELECT;
		MappedStatement.Builder statementBuilder = new MappedStatement.Builder(configuration,
		id, sqlSource, sqlCommandType)
		.resource(resource)
		.fetchSize(fetchSize)
		.timeout(timeout)
		.statementType(statementType)
		.keyGenerator(keyGenerator)
		.keyProperty(keyProperty)
		.keyColumn(keyColumn)
		.databaseId(databaseId)
		.lang(lang)
		.resultOrdered(resultOrdered)
		.resultSets(resultSets)
		.resultMaps(getStatementResultMaps(resultMap, resultType, id))
		.resultSetType(resultSetType)
		.flushCacheRequired(valueOrDefault(flushCache, !isSelect))
		.useCache(valueOrDefault(useCache, isSelect))
		.cache(currentCache);
		ParameterMap statementParameterMap = getStatementParameterMap(parameterMap,
		parameterType, id);
		if (statementParameterMap != null) {
			statementBuilder.parameterMap(statementParameterMap);
		} 
		MappedStatement statement = statementBuilder.build();
		//持有在configuration中
		configuration.addMappedStatement(statement);
		return statement;
}
public void addMappedStatement(MappedStatement ms){
//ms.getId = mapper.UserMapper.getUserById
//ms = MappedStatement等于每一个增删改查的标签的里的数据
	mappedStatements.put(ms.getId(), ms);
}
//最终存放到mappedStatements中,mappedStatements存放的是一个个的增删改查
protected final Map<String, MappedStatement> mappedStatements = new StrictMap<MappedStatement>("Mapped Statements collection").conflictMessageProducer((savedValue, targetValue) ->
". please check " + savedValue.getResource() + " and " + targetValue.getResource());

5.解析bindMapperForNamespace()方法

把namespace和工厂类绑定起来

private void bindMapperForNamespace() {
	//当前Mapper的命名空间
	String namespace = builderAssistant.getCurrentNamespace();
	if (namespace != null) {
		Class<?> boundType = null;
		try {
			//interface mapper.UserMapper这种
			boundType = Resources.classForName(namespace);
		} catch (ClassNotFoundException e) {
		} 
		if (boundType != null) {
			if (!configuration.hasMapper(boundType)) {
				configuration.addLoadedResource("namespace:" + namespace);
				configuration.addMapper(boundType);
			}
		}
	}
}
public <T> void addMapper(Class<T> type) {
	mapperRegistry.addMapper(type);
} 
public <T> void addMapper(Class<T> type) {
	if (type.isInterface()) {
		if (hasMapper(type)) {
			throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
		} 
		boolean loadCompleted = false;
		try {
			//接口类型(key)->工厂类
			knownMappers.put(type, new MapperProxyFactory<>(type));
			MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
			parser.parse();
			loadCompleted = true;
		} finally {
			if (!loadCompleted) {
				knownMappers.remove(type);
			}
		}
	}
}

6.生成SqlSessionFactory对象

XMLMapperBuilder.parse()方法,是对 Mapper 映射器的解析里面有两个方法:

  1. configurationElement()解析所有的子标签,最终解析Mapper.xml中的insert/update/delete/select标签的id(全路径)组成key和整个标签和数据连接组成MappedStatement存放到Configuration中的 mappedStatements这个map里面。

  2. bindMapperForNamespace()是把接口类型(interface mapper.UserMapper)和工厂类存到放MapperRegistry中的knownMappers里面。

  • SqlSessionFactory的创建

    直接把Configuration当做参数,直接new一个DefaultSqlSessionFactory。

    public SqlSessionFactory build(Configuration config) {
    	return new DefaultSqlSessionFactory(config);
    }
    
  • SqlSession的创建

    mybatis操作的时候跟数据库的每一次连接,都需要创建一个会话,我们用openSession()方法来创建。这个会话里面需要包含一个Executor用来执行 SQL。Executor又要指定事务类型和执行器的类型。

    • 如果配置的是 JDBC,则会使用Connection 对象的 commit()、rollback()、close()管理事务。
    • 如果配置成MANAGED,会把事务交给容器来管理,比如 JBOSS,Weblogic。
SqlSession sqlSession = sqlSessionFactory.openSession();

public SqlSession openSession() {
	//configuration中有默认赋值protected ExecutorType defaultExecutorType = ExecutorType.SIMPLE
	return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
}
<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>

7.创建Executor

//ExecutorType是SIMPLE,一共有三种SIMPLE(SimpleExecutor)、REUSE(ReuseExecutor)、BATCH(BatchExecutor)
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
	Transaction tx = null;
	try {
		//xml中的development节点
		final Environment environment = configuration.getEnvironment();
		//type配置的是Jbdc所以生成的是JbdcTransactionFactory工厂类
		final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
		//Jdbc生成JbdcTransactionFactory生成JbdcTransaction
		tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
		//创建CachingExecutor执行器
		final Executor executor = configuration.newExecutor(tx, execType);
		//创建DefaultSqlSession属性包括 Configuration、Executor对象
		return new DefaultSqlSession(configuration, executor, autoCommit);
	} catch (Exception e) {
		closeTransaction(tx); // may have fetched a connection so lets call
		close()
		throw ExceptionFactory.wrapException("Error opening session. Cause: " + e, e);
	} finally {
		ErrorContext.instance().reset();
	}
}

8.获得Mapper对象

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

public <T> T getMapper(Class<T> type) {
	return configuration.getMapper(type, this);
}
// mapperRegistry.getMapper是从MapperRegistry的knownMappers里面取的,knownMappers里面存的是接口类型(interface mapper.UserMapper)和工厂类(MapperProxyFactory)。
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
	return mapperRegistry.getMapper(type, sqlSession);
}
// 从knownMappers的Map里根据接口类型(interface mapper.UserMapper)取出对应的工厂类。
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
	final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>)
	knownMappers.get(type);
	if (mapperProxyFactory == null) {
		throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
	} 
	try {
		return mapperProxyFactory.newInstance(sqlSession);
	} catch (Exception e) {
		throw new BindingException("Error getting mapper instance. Cause: " + e, e);
	}
}
public T newInstance(SqlSession sqlSession) {
	final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface, methodCache);
	return newInstance(mapperProxy);
}
// 这里通过JDK动态代理返回代理对象MapperProxy(org.apache.ibatis.binding.MapperProxy@6b2ea799)
protected T newInstance(MapperProxy<T> mapperProxy) {
	//mapperInterface是interface mapper.UserMapper	
	return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new
	Class[] { mapperInterface }, mapperProxy);
}

9.执行SQL

调用代理方法

由于所有的 Mapper 都是 MapperProxy 代理对象,所以任意的方法都是执行MapperProxy 的invoke()方法

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
	try {
		//判断是否需要去执行SQL还是直接执行方法
		if (Object.class.equals(method.getDeclaringClass())) {
			return method.invoke(this, args);
			//这里判断的是接口中的默认方法Default等
		} else if (isDefaultMethod(method)) {
			return invokeDefaultMethod(proxy, method, args);
		}
	} catch (Throwable t) {
		throw ExceptionUtil.unwrapThrowable(t);
	} 
    //获取缓存,保存了方法签名和接口方法的关系
	final MapperMethod mapperMethod = cachedMapperMethod(method);
	return mapperMethod.execute(sqlSession, args);
}
调用execute方法

这里使用的例子用的是查询所以走的是else分支语句。

public Object execute(SqlSession sqlSession, Object[] args) {
	Object result;
	//根据命令类型走不行的操作command.getType()是select
	switch (command.getType()) {
		case INSERT: {
			Object param = method.convertArgsToSqlCommandParam(args);
			result = rowCountResult(sqlSession.insert(command.getName(), param));
			break;
		} 
		case UPDATE: {
			Object param = method.convertArgsToSqlCommandParam(args);
			result = rowCountResult(sqlSession.update(command.getName(), param));
			break;
		} 
		case DELETE: {
			Object param = method.convertArgsToSqlCommandParam(args);
			result = rowCountResult(sqlSession.delete(command.getName(), param));
			break;
		} 
		case SELECT:
			if (method.returnsVoid() && method.hasResultHandler()) {
				executeWithResultHandler(sqlSession, args);
				result = null;
			} else if (method.returnsMany()) {
				result = executeForMany(sqlSession, args);
			} else if (method.returnsMap()) {
				result = executeForMap(sqlSession, args);
			} else if (method.returnsCursor()) {
				result = executeForCursor(sqlSession, args);
			} else {
				//将参数转换为SQL的参数
				Object param = method.convertArgsToSqlCommandParam(args);
				result = sqlSession.selectOne(command.getName(), param);
				if (method.returnsOptional()
				&& (result == null ||
				!method.getReturnType().equals(result.getClass()))) {
					result = Optional.ofNullable(result);
				}
			}
			break;
		case FLUSH:
			result = sqlSession.flushStatements();
			break;
		default:
			throw new BindingException("Unknown execution method for: " + command.getName());
	} 
	if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {
		throw new BindingException("Mapper method '" + command.getName() + " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ").");
	} 
	return result;
}
selectOne同selectList
public <T> T selectOne(String statement, Object parameter) {
	// Popular vote was to return null on 0 results and throw exception on too many.
	List<T> list = this.selectList(statement, parameter);
	if (list.size() == 1) {
		return list.get(0);
	} else if (list.size() > 1) {
		throw new TooManyResultsException("Expected one result (or null) to be returned by selectOne(), but found: " + list.size());
	} else {
		return null;
	}
}

public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
	try {
		//从Configuration里的mappedStatements里根据key(id的全路径)获取MappedStatement 对象
		MappedStatement ms = configuration.getMappedStatement(statement);
		return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
	} catch (Exception e) {
		throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e);
	} finally {
		ErrorContext.instance().reset();
	}
}
query方法
创建CacheKey

从 BoundSql 中获取SQL信息,创建 CacheKey。这个CacheKey就是缓存的Key。

public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
	//创建缓存Key
	BoundSql boundSql = ms.getBoundSql(parameterObject);
	//key = -575461213:-771016147:mapper.UserMapper.getUserById:0:2147483647:select * from test_user where id = ?:1:development
	CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql);
	return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}

public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
	Cache cache = ms.getCache();
	if (cache != null) {
		flushCacheIfRequired(ms);
		if (ms.isUseCache() && resultHandler == null) {
			ensureNoOutParams(ms, boundSql);
			@SuppressWarnings("unchecked")
			List<E> list = (List<E>) tcm.getObject(cache, key);
			if (list == null) {
				list = delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
				tcm.putObject(cache, key, list); // issue #578 and #116
			} 
			return list;
		}
	}
	return delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}

清除本地缓存
public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
	ErrorContext.instance().resource(ms.getResource()).activity("executing a query").object(ms.getId());
	if (closed) {
		throw new ExecutorException("Executor was closed.");
	} 
	//queryStack 用于记录查询栈,防止递归查询重复处理缓存
	//flushCache=true 的时候,会先清理本地缓存(一级缓存)
	if (queryStack == 0 && ms.isFlushCacheRequired()) {
		//清空本地缓存
		clearLocalCache();
	} 
	List<E> list;
	try {
		queryStack++;
		list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;
		if (list != null) {
			handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);
		} else {
			//如果没有缓存,会从数据库查询:queryFromDatabase()
			list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);
		}
	} finally {
		queryStack--;
	} 
	if (queryStack == 0) {
		for (DeferredLoad deferredLoad : deferredLoads) {
		deferredLoad.load();
		} 
		// issue #601
		deferredLoads.clear();
		//如果 LocalCacheScope == STATEMENT,会清理本地缓存
		if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {
			// issue #482
			clearLocalCache();
		}
	} 
	return list;
}
从数据库查询
private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
	List<E> list;
	//先在缓存用占位符占位
	localCache.putObject(key, EXECUTION_PLACEHOLDER);
	try {
		//执行Executor 的 doQuery(),默认是SimpleExecutor
		list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);
	} finally {
		//执行查询后,移除占位符
		localCache.removeObject(key);
	} 
	//从新放入数据
	localCache.putObject(key, list);
	if (ms.getStatementType() == StatementType.CALLABLE) {
		localOutputParameterCache.putObject(key, parameter);
	} 
	return list;
}
执行doQuery
public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
	Statement stmt = null;
	try {
		Configuration configuration = ms.getConfiguration();
		StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
		stmt = prepareStatement(handler, ms.getStatementLog());
		return handler.query(stmt, resultHandler);
	} finally {
		closeStatement(stmt);
	}
}

Mybatis-Plus

中文文档:版本2-x https://baomidou.gitee.io/mybatis-plus-doc/#/

中文文档:版本3-x https://www.bookstack.cn/read/mybatis-plus-3.x/quickstart.md

PS:不仅是大版本之间有很大差异,即使是同个大版本的文档,不同的小版本也会出现不一样的用法和配置问题。

SpringBoot配置文件:

image-20220215104831936

  • 配置MapperScan

image-20220215110637898

selectMaps

  • 返回字段映射对象 Map 集合
@Test
public void testSelectMaps() {
    // selectMaps 返回字段映射对象的map集合。
    // 如果出现空值,默认不会显示,需要时设置 mybatis.configuration.call-setters-on-nulls=true
    List<Map<String, Object>> list = momentMapper.selectMaps(null);
    list.forEach(moment->logger.info(moment.toString()));
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-L2mAGZX3-1645602724512)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20220215160822502.png)]

selectBatchIds

  • 查询(根据ID 批量查询)
@Test
public void testSelectById() {
    List<Integer> idList = new ArrayList<>();
    idList.add(2119606340);
    idList.add(2119606341);
    // selectBatchIds 按照Id批量查询 
    // SELECT * FROM t_moment WHERE mid IN ( ? , ? )
    List<Moment> listById = momentMapper.selectBatchIds(idList);
    listById.forEach(moment -> logger.info(moment.toString()));
}

selectPage

  • 分页查询
@Test
    public void testSelectPage() {
        // 分页信息
        IPage<Moment> iPage = new Page<>(2,5);
        // 条件构造器
        QueryWrapper<Moment> queryWrapper = new QueryWrapper<>();
        // 加入条件,查找uid为6或8,且点赞数大于100的,按点赞排序
        queryWrapper.eq("uid",6)
            .or()
            .eq("uid",8)
            .lt("like_num",100)
            .orderByAsc("like_num");
        // 注意这里要在配置类中加入分页插件才能生效
        IPage<Moment> momentIPage = momentMapper.selectPage(iPage, queryWrapper);

        logger.info("一共查询了" + momentIPage.getTotal() + "条记录!");

        List<Moment> list = momentIPage.getRecords();
        list.forEach(moment -> logger.info(moment.toString()));
    }

注意:

  • 需要在配置类中加入分页插件,否则虽然不会报错但是分页不会生效(只会查询不会分页),同时配置类要注意版本问题。

    //Spring boot方式
    @Configuration
    public class MybatisPlusConfig {
        /**
            mybatis版本在3.4.0后改用以下配置
         */
        @Bean
        public MybatisPlusInterceptor mybatisPlusInterceptor() {
            MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
            interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
            return interceptor;
        }
    
        /* 旧版本配置
       @Bean
       public PaginationInterceptor paginationInterceptor(){
          return new PaginationInterceptor();
       }*/
    }
    

selectByMaps

  • 根据 columnMap 条件,查询记录
@Test
public void testSelectByMap() {
    Map<String,Object> map = new HashMap<>();
    map.put("uid",6);

    List<Moment> list = momentMapper.selectByMap(map);
    list.forEach(moment -> logger.info(moment.toString()));
}

deleteByMap

  • 根据 columnMap 条件,删除记录
@Test
public void testDeleteMaps() {
    Map<String,Object> map = new HashMap<>();
    // 删除满足map所示条件的数据
    // DELETE FROM t_moment WHERE uid = ? AND status_now = ?
    map.put("uid",9);
    map.put("status_now",0);

    int res = momentMapper.deleteByMap(map);
    logger.info("影响了" + res + "条记录!");
}

条件构造器

 queryWrapper.eq("uid",6)
            .or()
            .eq("uid",8)
            .lt("like_num",100)
            .orderByAsc("like_num");

问题和解决:

  1. 数据库主键自增时,要在实体类中设置:

image-20220215162009785
= momentIPage.getRecords();
list.forEach(moment -> logger.info(moment.toString()));
}


注意:

- 需要在配置类中加入分页插件,否则虽然不会报错但是分页不会生效(只会查询不会分页),同时配置类要注意版本问题。

  > ```java
  > //Spring boot方式
  > @Configuration
  > public class MybatisPlusConfig {
  >     /**
  >         mybatis版本在3.4.0后改用以下配置
  >      */
  >     @Bean
  >     public MybatisPlusInterceptor mybatisPlusInterceptor() {
  >         MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
  >         interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
  >         return interceptor;
  >     }
  > 
  >     /* 旧版本配置
  >    @Bean
  >    public PaginationInterceptor paginationInterceptor(){
  >       return new PaginationInterceptor();
  >    }*/
  > }
  > ```

## selectByMaps

- 根据 columnMap 条件,查询记录

```java
@Test
public void testSelectByMap() {
    Map<String,Object> map = new HashMap<>();
    map.put("uid",6);

    List<Moment> list = momentMapper.selectByMap(map);
    list.forEach(moment -> logger.info(moment.toString()));
}

deleteByMap

  • 根据 columnMap 条件,删除记录
@Test
public void testDeleteMaps() {
    Map<String,Object> map = new HashMap<>();
    // 删除满足map所示条件的数据
    // DELETE FROM t_moment WHERE uid = ? AND status_now = ?
    map.put("uid",9);
    map.put("status_now",0);

    int res = momentMapper.deleteByMap(map);
    logger.info("影响了" + res + "条记录!");
}

条件构造器

 queryWrapper.eq("uid",6)
            .or()
            .eq("uid",8)
            .lt("like_num",100)
            .orderByAsc("like_num");

问题和解决:

  1. 数据库主键自增时,要在实体类中设置:

[外链图片转存中…(img-jXy73NDQ-1645602724512)]

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值