mybatis学习笔记(二)动态sql

mapper.xml
动态查询

<select id="findUserListDy" parameterType="srj.po.Usersearch"
        resultType="srj.po.User">
        select * from userinfo
        <where>
            <if test="user!=null">
                <if test="user.name!=null and user.name!=''">
                    AND name=#{user.name}
                </if>
                <if test="user.grade!=null and user.grade!=''">
                    AND grade=#{user.grade}
                </if>
            </if>
        </where>
    </select>

原语句

<select id="findUserList" parameterType="srj.po.Usersearch" resultType="srj.po.User">
        select * from userinfo where name=#{user.name} and grade=#{user.grade}
</select>

where的效果如果拼接的条件成立 则自动省略第一个and

        <where>
            <if test="user!=null">//成立
                <if test="user.name!=null and user.name!=''">
                //成立
                    AND name=#{user.name}
                </if>
                <if test="user.grade!=null and user.grade!=''">
                //不成立
                    AND grade=#{user.grade}
                </if>
            </if>
        </where>

则最终语句为
select * from userinfo where name=#{user.name}
where省略了 AND name=#{user.name} 中的 and

如果所有条件都成立 则
select * from userinfo where name=#{user.name} and grade=#{user.grade}
省略了第一个and

猜你喜欢

转载自blog.csdn.net/qq_38189293/article/details/82531699
今日推荐