MyBatis中动态sql

本文介绍了MyBatis中动态SQL的实现。动态SQL可根据条件获取不同语句,主要是where部分变化。使用<if>、<where>、<foreach>等标签实现,还介绍了代码片段复用语句的方法,同时给出了各标签的语法和使用示例。

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

动态sql

sql的内容是变化的,可以根据条件获取到不同的sql语句,主要是where部分发生变化

动态sql的实现,使用的是mybatis提供的标签:<if>  <where>  <foreach>

动态SQL之<if>

语法

<if test="判断java对象的属性值">

部分sql语句

</if>

使用示例

<select id="selectUserIf" resultType="com.itheima.domain.User">
    select * from user
    where 1=1
    <if test="username != null and username != ''">
        username=#{username}
    </if>

    <if test="id > 0">
        and id=#{id}
    </if>
</select>

为什么要在where后面加上1=1,这是因为当第一个if中的条件不满而第二个if条件满足的时候,这个时候查询语句会变成如下

select * from user where 1=1 and id=#{id}

如果没在where后面加上1=1,这是因为当第一个if中的条件不满而第二个if条件满足的时候,这个时候查询语句会变成如下

select * from user where and id=#{id}

这种情况下sql语句就会报错

动态SQL之<where>

用来包含多个<if>的,当多个if有一个成立的,<where>会自动增加一个where关键字的,并去掉多余的and,or等。

使用示例

<select id="selectUserWhere" resultType="com.itheima.domain.User">
    select * from user
    <where>
        <if test="username != null and username != ''">
            username=#{username}
        </if>

        <if test="id > 0">
            and id=#{id}
        </if>
    </where>
</select>

动态SQL之<foreach>

循环java中的数组、list集合的,主要用在sql的in语句中。

1)循环list集合中的简单类型

前提接口中方法为:

List<User> selectForeachOne(List<Integer> idList);

mapper文件中的配置: 

<select id="selectForeachOne" resultType="com.itheima.domain.User">
    select * from user where id in
    <foreach collection="list" item="myid" open="(" close=")" separator=",">
        #{myid}
    </foreach>
</select>

colleaction:表示接口中方法参数的类型,如果是数组使用array,如果是list集合使用list

item:自定义,表示数组和集合成员的变量

open:循环开始时的字符

close:循环结束时的字符

separator:集合成员之间的分隔符

也可以下成下面的形式

<select id="selectForeachOne" resultType="com.itheima.domain.User">
    select * from user where id in(
    <foreach collection="list" item="myid" separator=",">
        #{myid}
    </foreach>
    )
</select>

最后拼接出的sql语句:

2)循环list集合中的对象,从对象中取出属性

前提:接口中的方法为

List<User> selectForeachTwo(List<User> idList);

mapper文件中的配置

<select id="selectForeachTwo" resultType="com.itheima.domain.User">
    select * from user where id in
    <foreach collection="list" item="user" open="(" close=")" separator=",">
        #{user.id}
    </foreach>
</select>

最后拼接出的sql语句:

动态SQL之代码片段 

sql代码片段,主要就是复用一些语句

步骤:

1、先使用<sql id="自定义名称唯一"> sql语句,表名,字段等</sql>

<!--    定义sql的片段-->
    <sql id="userSql">
        select * from user
    </sql>

2、再使用,<include refid="id的值" />

<select id="selectForeachOne" resultType="com.itheima.domain.User">
    <include refid="userSql"/>
    where id in(
    <foreach collection="list" item="myid" separator=",">
        #{myid}
    </foreach>
    )
</select>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值