Mybatis动态SQL

where、if、foreach的使用

IUserDao中写两个方法

	/**
     * 根据传入参数条件查询用户
     * 条件可能为id或username或其他或者全都有
     * @param user
     * @return
     */
    List<User> findUserCondition(User user);


    /**
     * 根据QueryVo集合中的id查询用户
     * @param qv
     * @return
     */
    List<User> findUserInIds(QueryVo qv);

QueryVo类

public class QueryVo {
    private User user;
    private List<Integer> ids;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

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

    public void setIds(List<Integer> ids) {
        this.ids = ids;
    }
}
if标签的使用
	<select id="findUserCondition" resultType="User" parameterType="User">
        select * from user where 1=1
        <if test="username != null">
            and username = #{username}
        </if>
        <if test="sex != null">
            and sex = #{sex}
        </if>
    </select>
where标签的使用
	<select id="findUserCondition" resultType="User" parameterType="User">
        select * from user
        <where>
            <if test="username != null">
                and username = #{username}
            </if>
            <if test="sex != null">
                and sex = #{sex}
            </if>
        </where>
    </select>
foreach标签的使用
	<select id="findUserInIds" resultType="user" parameterType="queryVo">
        select * from user
        <where>
            <if test="ids != null and ids.size()>0">
                <foreach collection="ids" open="and id in (" close=")" item="id" separator=",">
                    #{id}
                </foreach>
            </if>
        </where>
    </select>

配置好之后测试类中使用相应方法测试即可。

sql标签的使用

sql标签用于封装重复的sql语句.

	<sql id="defaultSelect">
        select * from user
    </sql>


	<!--调用-->
	<include refid="defaultSelect"></include>
上一篇:Mybatis入门笔记(6)——动态SQL


下一篇:Validates using resource IDs in a switch statement in Android library module