mybatis trim 使用

trim可以去除sql语句中多余的and关键字,逗号,或者给sql语句前拼接 “where“、“set“以及“values(“ 等前缀,或者添加“)“等后缀,可用于选择性插入、更新、删除或者条件查询等操作。

    <update id="update" parameterType="Product">
        update
        <include refid="tableName"></include>
        <trim prefix="set" suffixOverrides=",">
            <if test="product_name!=null and product_name != ''">product_name = #{product_name},</if>
            <if test="product_code!=null and product_code != ''">product_code = #{product_code},</if>
        </trim>
        where product_id = #{product_id}
    </update>
    
    <insert id="add" parameterType="Product">
        insert into <include refid="tableName"></include>
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="product_id != null and product_id !=''">product_id,</if>
            <if test="product_name != null and product_name !=''">product_name, </if>
            <if test="product_code != null and product_code !=''">product_code, </if>

        </trim>
        <trim prefix="values(" suffix=")" suffixOverrides=",">
            <if test="product_id != null and product_id !=''">#{product_id},</if>
            <if test="product_name != null and product_name !=''">#{product_name},</if>
            <if test="product_code != null and product_code !=''">#{product_code}, </if>
        </trim>
    </insert>

 

posted @ 2021-09-08 16:09  ジ绯色月下ぎ  阅读(289)  评论(0编辑  收藏  举报