首页 > 技术文章 > MyBatis动态插入的实现

charlottepl 原文

mybatis通过定义前缀后缀和分割字符来拼接sql语句,实现动态插入的功能

<insert id="addNewsTypeByNewsId">
        insert into news_newstype

        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="newsId != null">
                newsid,
            </if>
            <if test="newsTypeId != null and newsTypeId !=0">
                newstypeid,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="newsId != null">
                #{newsId},
            </if>
            <if test="newsTypeId != null and newsTypeId !=0">
                #{newsTypeId},
            </if>
        </trim>
    </insert>

推荐阅读