Mybatis动态SQL

Mybatis动态SQL提供了解决字符串拼接SQL痛点的功能,包括if、where、choose、when、otherwise和foreach等标签。本文详细介绍了这些标签的用法,如if标签的条件判断,where标签避免多余的and,choose标签的if...else逻辑,以及foreach标签在批量操作中的应用,并给出了实际示例和最佳实践。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Mybatis动态SQL

Mybatis框架的动态SQL技术是一种根据特定条件动态拼装SQL语句的功能,它存在的意义是为了解决 拼接SQL语句字符串时的痛点问题。

if

if标签可通过test属性的表达式进行判断,若表达式的结果为true,则标签中的内容会执行;反之标签中的内容不会执行

if,通过test属性中的表达式判断标签中的内容是否有效(是否会拼接到sql中)

public interface DynamicSQLMapper {

    /**
     * 根据条件查询员工信息
     * @param emp
     * @return
     */
    List<Emp> getEmpByCondition(Emp emp);
}
<?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.example.mybatis.mapper.DynamicSQLMapper">
    <select id="getEmpByCondition" resultType="Emp">
        select * from t_emp where
        <if test="empName != null and empName != ''">
            and emp_name = #{empName}
        </if>
        <if test="age != null and age != ''">
            and age = #{age}
        </if>
        <if test="gender != null and gender != ''">
            and gender = #{gender}
        </if>
    </select>
</mapper>

以上的SQL会在某个if标签的条件不成立时,就会抛出异常,从而导致查不出数据,解决方案,在where后添加1=1的条件,如下

<select id="getEmpByCondition" resultType="Emp">
        select * from t_emp where 1=1
        <if test="empName != null and empName != ''">
            and emp_name = #{empName}
        </if>
        <if test="age != null and age != ''">
            and age = #{age}
        </if>
        <if test="gender != null and gender != ''">
            and gender = #{gender}
        </if>
    </select>

或者结合where标签进行动态实现,下面会给出。

where

where标签中有条件成立,则会自动生成where关键字,同时where标签中第一个if标签的条件不成立,则不会用and关键字来拼接该if标签的内容,会自动将where标签中内容前多余的and去掉,但不会将其中内容后的and去掉,若所有if标签的条件均不成立,这时SQL语句变成了select * from t_emp,此时where标签没有任何功能

<?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.example.mybatis.mapper.DynamicSQLMapper">
    <select id="getEmpByCondition" resultType="Emp">
        select * from t_emp
        <where>
            <if test="empName != null and empName != ''">
                emp_name = #{empName}
            </if>
            <if test="age != null and age != ''">
                and age = #{age}
            </if>
            <if test="gender != null and gender != ''">
                and gender = #{gender}
            </if>
        </where>
    </select>
</mapper>

例如如下的写法将and写在后面,当and后面的if标签的条件不成立时就会报错,原因:where标签不会将其中内容后的and去掉

<?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.example.mybatis.mapper.DynamicSQLMapper">
    <select id="getEmpByCondition" resultType="Emp">
        select * from t_emp
        <where>
            <if test="empName != null and empName != ''">
                emp_name = #{empName} and
            </if>
            <if test="age != null and age != ''">
                 age = #{age} and
            </if>
            <if test="gender != null and gender != ''">
                 gender = #{gender}
            </if>
        </where>
    </select>
</mapper>

解决where标签不会将其中内容后的and去掉的方法,需要结合trim来使用,下面会给出

trim

trim用于去掉或添加标签中的内容

常用属性:

prefix:在trim标签中的内容的前面添加某些内容

prefixOverrides:在trim标签中的内容的前面去掉某些内容

suffix:在trim标签中的内容的后面添加某些内容

suffixOverrides:在trim标签中的内容的后面去掉某些内容

<?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.example.mybatis.mapper.DynamicSQLMapper">
    <select id="getEmpByCondition" resultType="Emp">
        select * from t_emp
        <trim prefix="where" suffixOverrides="and">
            <if test="empName != null and empName != ''">
                emp_name = #{empName} and
            </if>
            <if test="age != null and age != ''">
                age = #{age} and
            </if>
            <if test="gender != null and gender != ''">
                gender = #{gender}
            </if>
        </trim>
    </select>
</mapper>

choose、when、otherwise

choose、when、 otherwise相当于Java中的if…else if…else,when至少设置一个,otherwise最多设置一个

使用choose、when、 otherwise,只要when标签中有一个条件成立后,面when标签的条件就不进行判断了

public interface DynamicSQLMapper {
    /**
     * 使用choose查询员工信息
     * @param emp
     * @return
     */
    List<Emp> getEmpByChoose(Emp emp);
}

<?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.example.mybatis.mapper.DynamicSQLMapper">
     <!--List<Emp> getEmpByChoose(Emp emp);-->
    <select id="getEmpByChoose" resultType="Emp">
        select * from t_emp
        <where>
            <choose>
                <when test="empName != null and empName != ''">
                    emp_name = #{empName}
                </when>
                <when test="age != null and age != ''">
                    age = #{age}
                </when>
                <when test="gender != null and gender != ''">
                    gender = #{gender}
                </when>
            </choose>
        </where>
    </select>
</mapper>

foreach

collection:设置要循环的数组或集合
item:用一个字符串表示数组或集合中的每一个数据(也就是遍历集合或数组中的值)
separator:设置每次循环的数据之间的分隔符
open:循环的所有内容以什么开始
close:循环的所有内容以什么结束

批量添加

public interface DynamicSQLMapper {

    /**
     * 批量添加员工信息
     * @param emps
     */
    void insertMoreEmp(@Param("emps") List<Emp> emps);
}
<?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.example.mybatis.mapper.DynamicSQLMapper">
     <!--void insertMoreEmp(@Param("emps") List<Emp> emps);-->
    <insert id="insertMoreEmp">
        insert into t_emp values
        <foreach collection="emps" item="emp" separator=",">
            (null,#{emp.empName},#{emp.age},#{emp.gender},null)
        </foreach>
    </insert>
</mapper>

注意:若collection的属性值等于mapper接口中对应方法的参数值时,mapper方法中的参数必须使用@Param注解,原因是:mapper方法中的参数使用@Param注解后collection的属性值等于@Param的值,这时是以map集合来存储,由于方法参数的类型是List,此时会以list作为map的键(key),遍历出来的结果作为map的值(value),因此,collection的属性值等于@Param的值即可,要不然就要写对应集合或数组类型,若mapper接口中的insertMoreEmp方法的参数不使用@Param注解时,foreach循环应该这样写

<?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.example.mybatis.mapper.DynamicSQLMapper">
     <!--void insertMoreEmp(@Param List<Emp> emps);-->
    <insert id="insertMoreEmp">
        insert into t_emp values
        <foreach collection="list" item="emp" separator=",">
            (null,#{emp.empName},#{emp.age},#{emp.gender},null)
        </foreach>
    </insert>
</mapper>

注意:以上由于mapper接口方法的参数类型时对象的List集合,故foreach标签遍历出来的的item的值也是一个对象,因此,在用#{}来接收参数时要特别注意,这里的Emp对象有,empName,age,gender等属性,故#{}中的内容要写成emp.age,emp.age,emp.gender,切记不要写成emp

批量删除

public interface DynamicSQLMapper {

    /**
     * 批量删除
     * @param empIds
     */
    void deleteMoreEmp(@Param("empIds") Integer[] empIds);
}

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.example.mybatis.mapper.DynamicSQLMapper">
    <!--void deleteMoreEmp(@Param("empIds") Integer[] empIds);-->
    <delete id="deleteMoreEmp">
        delete from t_emp where emp_id in
        <foreach collection="empIds" item="empId" separator="," open="(" close=")">
            #{empId}
        </foreach>
       
    </delete>
</mapper>

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.example.mybatis.mapper.DynamicSQLMapper">
    <!--void deleteMoreEmp(@Param("empIds") Integer[] empIds);-->
    <delete id="deleteMoreEmp">
        delete from t_emp where
        <foreach collection="empIds" item="empId" separator="or">
            emp_id = #{empId}
        </foreach>
    </delete>
</mapper>

注意:若collection的属性值等于mapper接口中对应方法的参数值时,mapper方法中的参数必须使用@Param注解,要不然就要写对应集合或数组类型,若mapper接口中的insertMoreEmp方法的参数不使用@Param注解时,foreach循环应该这样写

<?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.example.mybatis.mapper.DynamicSQLMapper">
    <!--void deleteMoreEmp(Integer[] empIds);-->
    <delete id="deleteMoreEmp">
        delete from t_emp where
        <foreach collection="array" item="empId" separator="or">
            emp_id = #{empId}
        </foreach>
    </delete>
</mapper>

注意:由于mapper接口方法参数的类型是数组类型,而且没有使用@Param注解,故collection=“array”,诀窍:若mapper接口的方法没有使用@Param注解时,foreach的collection属性值就要等于mapper接口的方法参数类型的小写形式即可

SQL片段

sql片段,可以记录一段公共sql片段,在使用的地方通过include标签进行引入

<sql id="empColumns"> eid,ename,age,sex,did </sql> 

select <include refid="empColumns"></include> from t_emp

注意:include标签中refid的值要指向sql标签中id的值

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值