MyBatis之动态SQL

if 和 where

public interface UserDao {
    List<User> getUserListByCondition(User user);
}
<select id="getUserListByCondition" parameterType="User" resultType="User">
    select id, username, birthday, sex, address from user
    <where>
        <if test="username != null">
            and username = #{username}
        </if>
        <if test="sex != null">
            and sex = #{sex}
        </if>
    </where>
</select>

foreach

public interface UserDao {
    List<User> getUserListByIds(QueryVo vo);
}
package com.ttpfx.domain;

import java.util.List;

public class QueryVo {
    private List<Integer> ids;

    public List<Integer> getIds() {
        return ids;
    }

    public void setIds(List<Integer> ids) {
        this.ids = ids;
    }
}
<select id="getUserListByIds" parameterType="QueryVo" resultType="User">
        select id, username, birthday, sex, address from user
    <where>
        <if test="ids != null and ids.size() > 0">
            <foreach collection="ids" item="id" open="and id in (" separator="," close=")">
                #{id}
            </foreach>
        </if>
    </where>
</select>

参考

https://mybatis.org/mybatis-3/zh/dynamic-sql.html

posted @ 2021-03-09 11:53  ttpfx  阅读(42)  评论(0编辑  收藏  举报