一、if标签

<select id="queryEmpByCondition" resultType="User">
        select * from t_user where 1=1
        <if test="username != null and username != ''">
            and username = #{username}
        </if>
    </select>
@Test
    public void test3(){
        SqlSession sqlSession = SqlSessionUtils.sqlSession();
        DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
        User admin = new User(null, "admin", null, null, null, null);
        List<User> users = mapper.queryEmpByCondition(admin);
        System.out.println(users);

    }

 二、where标签

条件内容前的and或or

select id="queryEmpByCondition" resultType="User">
        select * from t_user
        <where>
        <if test="username != null and username != ''">
            and username = #{username}
        </if>
       </where>
    </select>

Java --- Mybatis的动态sql标签-LMLPHP

 条件内容后的and或or

<select id="queryEmpByCondition" resultType="User">
        select * from t_user
        <where>
        <if test="username != null and username != ''">
             username = #{username} and
        </if>
       </where>
    </select>

Java --- Mybatis的动态sql标签-LMLPHP

三、trim标签

<select id="queryEmpByCondition" resultType="User">
        select * from t_user
        <trim prefix="where"  suffixOverrides="and|or" >
            <if test="username != null and username != ''">
                username = #{username} and
            </if>
        </trim>
    </select>

四、choose、when、otherwise标签 

<select id="queryEmpByCondition" resultType="User">
        select * from t_user
        <trim prefix="where"  suffixOverrides="and|or" >
            <choose>
                <when test="username != null and username != ''">
                    username = #{username}
                </when>
                <when test="password != null and password != ''">
                    password = #{password}
                </when>
                <otherwise>
                    id = 1
                </otherwise>
            </choose>
        </trim>
    </select>

五、foreach标签 

批量删除:

形式一

<mapper namespace="com.cjc.ssm.mapper.DynamicSQLMapper">
    <delete id="removeByUserArray">
        delete from t_user where id in
        <foreach collection="arr" item="id" separator="," open="(" close=")">
            #{id}
        </foreach>
    </delete>

 形式二

<delete id="removeByUserArray">
        delete from t_user where
        <foreach collection="arr" item="id" separator="or">
            id = #{id}
        </foreach>
    </delete>

批量添加

 <insert id="addUserList">
        insert into t_user values
        <foreach collection="list" item="user" separator=",">
         (null,#{user.username},#{user.password},#{user.age},#{user.sex},#{user.email})
        </foreach>
    </insert>

六、sql标签 

Java --- Mybatis的动态sql标签-LMLPHP

11-09 14:35