mybatis常用(动态)SQL操作样例

插入数据并返回主键

<!--
     添加操作
        默认返回的饿是受影响的行数,可以设置返回主键(自动增长)
        useGeneratedKeys:取值范围是true或false,表示会获取主键,并赋值到keyProperty属性设置的模型属性(JavaBean实体类中的属性字段)
        keyProperty:设置返回值将赋值给数据属性的哪个属性字段
        keyColumn:设置数据库自动生动的朱主键名

        返回的主键会自动设置到实体类中对应的id属性字段中
  -->
<insert id="insertSelective" parameterType="com.xxxx.crm.vo.User" useGeneratedKeys="true" keyProperty="id" keyColumn="id" >
    insert into t_user
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="userName != null" >
        user_name,
      </if>
      <if test="userPwd != null" >
        user_pwd,
      </if>
      <if test="trueName != null" >
        true_name,
      </if>
      <if test="email != null" >
        email,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=INTEGER},
      </if>
      <if test="userName != null" >
        #{userName,jdbcType=VARCHAR},
      </if>
      <if test="userPwd != null" >
        #{userPwd,jdbcType=VARCHAR},
      </if>
      <if test="trueName != null" >
        #{trueName,jdbcType=VARCHAR},
      </if>
      <if test="email != null" >
        #{email,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>

多条件查询

<select id="selectByParams" parameterType="com.xxxx.crm.query.UserQuery" resultType="com.xxxx.crm.vo.User">
    select
        <include refid="Base_Column_List"></include>
    from
        t_user
    <where>
      is_valid = 1
      <!-- 用户名查询 -->
      <if test="null != userName and userName != ''">
        and user_name like concat('%',#{userName},'%')
      </if>
      <!-- 邮箱查询 -->
      <if test="null != email and email != ''">
        and email like concat('%',#{email},'%')
      </if>
      <!-- 手机号查询 -->
      <if test="null != phone and phone != ''">
        and phone like concat('%',#{phone},'%')
      </if>
    </where>
  </select>

遍历id逻辑删除

<update id="deleteBatch">
    update
        t_user
    set
        is_valid = 0
    where
        id
    in
        <foreach collection="array" item="id" open="(" close=")" separator=",">
          #{id}
        </foreach>
  </update>

条件更新

<update id="updateByPrimaryKeySelective" parameterType="com.xxxx.crm.vo.User" >
    update t_user
    <set >
      <if test="userName != null" >
        user_name = #{userName,jdbcType=VARCHAR},
      </if>
      <if test="userPwd != null" >
        user_pwd = #{userPwd,jdbcType=VARCHAR},
      </if>
      <if test="trueName != null" >
        true_name = #{trueName,jdbcType=VARCHAR},
      </if>
      <if test="email != null" >
        email = #{email,jdbcType=VARCHAR},
      </if>
      <if test="phone != null" >
        phone = #{phone,jdbcType=VARCHAR},
      </if>
      <if test="isValid != null" >
        is_valid = #{isValid,jdbcType=INTEGER},
      </if>
      <if test="createDate != null" >
        create_date = #{createDate,jdbcType=TIMESTAMP},
      </if>
      <if test="updateDate != null" >
        update_date = #{updateDate,jdbcType=TIMESTAMP},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>

批量添加


<insert id="insertBatch">
    insert into
        t_user_role (user_id,role_id,create_date,update_date)
    values
        <foreach collection="list" item="item" separator=",">
          (#{item.userId},#{item.roleId},now(),now())
        </foreach>
  </insert>

批量更新

第一种:
case when虽然最后只会有一条更新语句,但是xml中的循环体有点多,每一个case when 都要循环一遍list集合,所以大批量拼sql的时候会比较慢,所以效率问题严重。使用的时候建议分批插入。


    <!-- 批量更新第一种方法,通过 case when语句变相的进行批量更新 -->
<update id="updateBatch" parameterType="list">
    update roughnes
    <trim prefix="set" suffixOverrides=",">
      <trim prefix="p1_roughness =case" suffix="end,">
        <foreach collection="list" item="i" index="index">
          <if test="i.p1Roughness != null and i.p1Roughness !=''">
            when id = #{i.id} then #{i.p1Roughness}
          </if>
        </foreach>
      </trim>
      <trim prefix="p2_roughness =case" suffix="end,">
        <foreach collection="list" item="i">
          <if test="i.p2Roughness != null and i.p2Roughness != ''">
            when id = #{i.id} then #{i.p2Roughness}
          </if>
        </foreach>
      </trim>
      <trim prefix="p3_roughness =case" suffix="end,">
        <foreach collection="list" item="i">
          <if test="i.p3Roughness != null and i.p3Roughness != ''">
            when id = #{i.id} then #{i.p3Roughness}
          </if>
        </foreach>
      </trim>
      <trim prefix="p4_roughness =case" suffix="end,">
        <foreach collection="list" item="i">
          <if test="i.p4Roughness != null and i.p4Roughness != ''">
            when id = #{i.id} then #{i.p4Roughness}
          </if>
        </foreach>
      </trim>
      <trim prefix="p5_roughness =case" suffix="end,">
        <foreach collection="list" item="i">
          <if test="i.p5Roughness != null and i.p5Roughness != ''">
            when id = #{i.id} then #{i.p5Roughness}
          </if>
        </foreach>
      </trim>
      <trim prefix="average_roughne =case" suffix="end,">
        <foreach collection="list" item="i">
          <if test="i.averageRoughne != null and i.averageRoughne != ''">
            when id = #{i.id} then #{i.averageRoughne}
          </if>
        </foreach>
      </trim>
    </trim>
    where id in
    <foreach collection="list" item="i" separator="," open="(" close=")">
       #{i.id}
    </foreach>
  </update>

第二种:
sql语句for循环效率其实相当高的,因为它仅仅有一个循环体,只不过最后update语句比较多,量大了就有可能造成sql阻塞。

<!-- 批量更新第二种方法,通过接收传进来的参数list进行循环着组装sql -->
     <update id="updateBatch" parameterType="java.util.List" >
        <foreach collection="list" item="item" index="index" open="" close="" separator=";">
            update standard_relation
            <set >
                <if test="item.standardFromUuid != null" >
                    standard_from_uuid = #{item.standardFromUuid,jdbcType=VARCHAR},
                </if>
                <if test="item.standardToUuid != null" >
                    standard_to_uuid = #{item.standardToUuid,jdbcType=VARCHAR},
                </if>
                <if test="item.gmtModified != null" >
                    gmt_modified = #{item.gmtModified,jdbcType=TIMESTAMP},
                </if>
            </set>
            where id = #{item.id,jdbcType=BIGINT}
        </foreach>
    </update>

第三种:
duplicate key update可以看出来是最快的,但是一般大公司都禁用,公司一般都禁止使用replace into和INSERT INTO … ON DUPLICATE KEY UPDATE,这种sql有可能会造成数据丢失和主从上表的自增id值不一致。而且用这个更新时,记得一定要加上id,而且values()括号里面放的是数据库字段,不是java对象的属性字段。

<!-- 批量更新第三种方法,用ON DUPLICATE KEY UPDATE-->
<insert id="updateBatch">
    insert into followme_parameters
    (id,account,chart_id,signal_source,rate)
    values
    <foreach collection="list" separator="," index="index" item="item">
        (#{item.id},#{item.account},#{item.chartId},#{item.signalSource},#{item.rate})
    </foreach>
    
    ON duplicate KEY UPDATE
    id=VALUES(id),signal_source=values(signal_source),rate=values(rate) 
</insert>

猜你喜欢

转载自blog.csdn.net/qq_25905159/article/details/112566415