Mybatis中的动态Sql

where和if

作用

where标签相当于where关键字,用它可以去除掉第一个and
if就是一个条件判断,满足条件,则会拼接if标签里面的sql语句

例子

多条件查询user信息

    <select id="findUsers" parameterType="UserQueryVo" resultMap="userMap">
        select id ,username username_,birthday birthday_,sex sex_,address address_
        from user
        <where>
            <if test="user!=null">
                <if test="user.username!=null and user.username!=''">
                    and user.username like '%${user.username}%'
                </if>
                <if test="user.sex!=null and user.sex!=''">
                    and user.sex = #{user.sex}
                </if>
            </if>
        </where>
    </select>

sql片段

作用

  • 可以将单表的查询的列的信息定义成一个sql片段,这样可以提高公用性
  • 可以将用户查询的片段定义成sql片段,如多条件查询的时候的where里面的if

注意:别将where也放在sql片段里面,因为很有可能以后需要对这个方法进行扩展,还会添加一些不属于user的属性的过滤信息,这个时候就会定义另外一个sql片段,然后将这个sql片段引用到where标签内,但是如果一开始就将where放在了user查询信息的where标签内,后面则无法进行扩展

    <sql id="find_Users_where">
        <if test="user!=null">
            <if test="user.username!=null and user.username!=''">
                and user.username like '%${user.username}%'
            </if>
            <if test="user.sex!=null and user.sex!=''">
                and user.sex = #{user.sex}
            </if>
        </if>
    </sql>

    <!--因为这个userMap是定义在这个文件里面的,所以可以直接使用,否则应该加上namespace-->
    <select id="findUsers" parameterType="UserQueryVo" resultMap="userMap">
        select id ,username username_,birthday birthday_,sex sex_,address address_
        from user
        <where>
            <include refid="find_Users_where"></include>
        </where>
    </select>

foreach

作用

foreach可以循环获取parameterType的集合属性里面的条件
例如:查询在ids集合里面的id的user信息,即id in(ids[0],ids[1],…)

    <select id="findUsersByIds" parameterType="UserQueryVo" resultType="user">
        select * from user
        <where>
        <!--如果传递进来的ids的长度为2,那么拼接成的preparedStatement就是
            select * from user WHERE id in ( ? , ? ) -->
            <if test="ids!=null and ids.size > 0">
                <foreach collection="ids" open="id in (" close=")" item="id" separator=",">
                    #{id}
                </foreach>
            </if>
        </where>
    </select>
public class UserQueryVo {
    private User user;
    private List<Integer> ids;  
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值