Mybatis中使用<SQL></SQL>公共引用

Mybatis中使用<SQL></SQL>公共引用

简述: SQL 标签是用于抽取可重用的 SQL 片段,将相同的,使用频繁的 SQL 片段抽取出来,单独定义,方便多次引用。抽取可重用的sql片段。方便后面引用 sql抽取:经常将要查询的列名,或者插入用的列名抽取出来方便引用 include来引用已经抽取的sql
使用场景: 在企业开发中,我们需要写一些复杂的SQL查询语句,可能在一个XML中会有多个SQL语句的条件不同但是查询条件的内容不同等,我们可以使用Mybatis中的<sql></sql>来实现公共的SQL引用

我们来简单演示一下如何使用SQL标签

一、Mapper.xml

定义公共<sql>
<?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.ywt.springboot.mapper.StudentMapper">
    <sql id="publicSQL">
        select * from student
    </sql>
</mapper>

二、Mapper

public interface StudentMapper {
          
   
    List<Student> queryOne(Integer id);
    List<Student> queryTwo(Integer id);
}

引用<sql>

<?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.ywt.springboot.mapper.StudentMapper">
    <sql id="publicSQL">
        select *
        from student
    </sql>

    <select id="queryOne" resultType="student">
        <include refid="publicSQL"/>
        where id = #{id}
    </select>
    <select id="queryTwo" resultType="student">
        <include refid="publicSQL"/>
        where id = #{id}
    </select>
</mapper>
<include>中的refid需要指向<sql>id的value

三.测试

@Test
    void select() {
          
   
        List<Student> listOne = studentMapper.queryOne(7);
        List<Student> listTwo = studentMapper.queryTwo(9);

        System.out.println("listOne:" + listOne.toString());
        System.out.println("listTwo:" + listTwo.toString());
    }
输出结果
经验分享 程序员 微信小程序 职场和发展