Mybatis 动态SQL IF判断&OGNL & WHERE

文章目录

<!-- 携带了哪个字段查询条件就带上哪个字段的值 -->
<select id="getEmpByConditionIf" resultType="com.mxthd.mybatis.bean.Employee">
    select * from tab_empoyee 
    where 1=1

    <if test="id!=null">
        and id = #{id}
    </if>
    <if test="lastName!=null and lastName!=''">
        and last_name like #{lastName}
    </if>
    <if test="email!=null and email.trim()!=''">
        and email = #{email}
    </if>
    <!-- ognl会自动进行字符串与数字的转换判断 "0"==0 -->
    <if test="gender==0 or gender==1">
        and gender=#{gender}
    </if>

</select>

WHERE

mybatis推荐写法

<!-- 携带了哪个字段查询条件就带上哪个字段的值 -->
<!-- 携带了哪个字段查询条件就带上哪个字段的值 -->
<select id="getEmpByConditionIf" resultType="com.mxthd.mybatis.bean.Employee">
    select * from tab_empoyee
    <where>
        <if test="id!=null">
            id = #{id}
        </if>
        <if test="lastName!=null and lastName!=''">
            and last_name like #{lastName}
        </if>
        <if test="email!=null and email.trim()!=''">
            and email = #{email}
        </if>
        <!-- ognl会自动进行字符串与数字的转换判断 "0"==0 -->
        <if test="gender==0 or gender==1">
        and gender=#{gender}
        </if>
    </where>
</select>
原文链接:,转发请注明来源!

发表评论