Mybatis的动态SQL

注意事项:

进行字符串是否为空判断时,不仅要考虑是否为null还要考虑空串的情况

条件表达式是判断对象属性是否符合条件,而SQL语句是对字段名的操作. 对象属性小驼峰命名,字段名以下划线分隔,注意区分

< If >

< if > : 用于判断条件是否成立. .使用 test 属性进行条件判断 , 如果条件为 true ,则拼接SQL
格式:
< if test = "条件表达式" >

SQL语句

< /if >

< Where >

< Where > : where 元素只会在子元素有内容的情况下才插入where子句.而且会自动去除子句开头的AND 或 OR
格式:
< where >

条件

< /where >

< Set >

< Set > : 动态的在行首插入 SET 关键字, 并会删掉格外的逗号. (用在update 语句中)
格式 :
< set >

条件

< /set >

< foreach >

属性:

collection : 集合名称

item : 集合遍历出来的元素 / 项 ,临时变量

separator : 每一次遍历使用的分隔符

open : 遍历开始前拼接的片段

close : 遍历结束后拼接的片段

格式 :
< foreach collection = "" item = "" separator = "" open = "" close = "">
遍历操作
< /foreach >
SQL语句
delete from emp where id in (1 , 2 , 3)
接口方法
//批量删除
public void DeleteByIds(List<Integer> ids);
XML映射文件
<delete id="DeleteByIds"  >
    delete
    from emp
    where id in
    <foreach collection="ids" item="id" separator="," open="(" close=")">
        #{id}
    </foreach>
</delete>

SQL片段

< sql > : 定义可重用的 SQL 片段.
< include > : 通过属性 refid , 指定包含的 sql 片段
注意事项 :

sql标签必须指定id 属性

include标签的 refid 属性 可以根据id可以找到对应的sql片段

测试类

@Test
void selectConditions() {
    List<Emp> z = empmapper.selectConditions("张", (short) 1, LocalDate.of(2002, 01, 01), LocalDate.of(2020, 01, 01));
    System.out.println(z);

}
@Test
void selectConditionsPlus() {
    List<Emp> z = empmapper.selectConditionsplus("张", null, null, null);
    System.out.println(z);
}

XML映射文件

<sql id="selectemp">
    select *
    from emp
</sql>

<select id="selectConditions" resultType="com.example.mybatis.pojo.Emp">
    <include refid="selectemp"/>
    where name like concat('%', #{name}, '%')
    and gender = #{gender}
    and entrydate between #{begin} and #{end};
</select>

<select id="selectById" resultType="com.example.mybatis.pojo.Emp">
    <include refid="selectemp"/>
    where id = #{id}
</select>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值