mybatis入门篇(二):mybatis动态SQL

1、if用法

<select id="selectUser" resultType="com.forest.owl.entity.User">
    select * from user
    where 1=1
    <if test="userName != null and userName != '' ">
        and user_name like concat('%', #{userName}, '%')
    </if>
    <if test="userPhone != null and userPhone !='' ">
        and user_phone=#{userPhone}
    </if>
</select>

2、choose

<select id="selectUser" resultType="com.forest.owl.entity.User">
    select * from user
    where 1=1
    <choose>
        <when test="id != null">
            and id=#{id}
        </when>
        <when test="userName != null and userName !='' ">
            and user_name=#{userName}
        </when>
        <otherwise>
            and 1=2
        </otherwise>
    </choose>
</select>

 3、where

where标签内如果没有符合条件的选项,则最后生成的sql语句不含where;如果有符合条件的,则生成的sql语句会自动去除两端的and

<select id="selectUser" resultType="com.forest.owl.entity.User">
    select * from user
    <where>
        <if test="userName != null and userName != '' ">
        and user_name like concat('%', #{userName}, '%')
        </if>
        <if test="userEmail != null and userEmail != '' ">
        and user_email = #{userEmail}
        </if>
    </where>
</select>

猜你喜欢

转载自www.cnblogs.com/wsfu/p/10662230.html