insertSelective和 insert的区别

(update 和 updateSelective 也一样)
先粘贴一段源码:(来源与generator自动生成的mapper文件里面的)
insert:

  <insert id="insert" keyColumn="agent_id" keyProperty="agentId" parameterType="com.vic.pro.lmy.entity.Agent" useGeneratedKeys="true">
    insert into agent (agent_name, clientKey, agent_conn_people,
      agent_phonenumber, create_time, delete_status
      )
    values (#{agentName,jdbcType=VARCHAR}, #{clientkey,jdbcType=VARCHAR}, #{agentConnPeople,jdbcType=VARCHAR},
      #{agentPhonenumber,jdbcType=VARCHAR}, #{createTime,jdbcType=TIMESTAMP}, #{deleteStatus,jdbcType=VARCHAR}
      )
  </insert>

insertSelective:

<insert id="insertSelective" keyColumn="agent_id" keyProperty="agentId" parameterType="com.vic.pro.lmy.entity.Agent" useGeneratedKeys="true">
    insert into agent
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="agentName != null">
        agent_name,
      </if>
      <if test="clientkey != null">
        clientKey,
      </if>
      <if test="agentConnPeople != null">
        agent_conn_people,
      </if>
      <if test="agentPhonenumber != null">
        agent_phonenumber,
      </if>
      <if test="createTime != null">
        create_time,
      </if>
      <if test="deleteStatus != null">
        delete_status,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="agentName != null">
        #{agentName,jdbcType=VARCHAR},
      </if>
      <if test="clientkey != null">
        #{clientkey,jdbcType=VARCHAR},
      </if>
      <if test="agentConnPeople != null">
        #{agentConnPeople,jdbcType=VARCHAR},
      </if>
      <if test="agentPhonenumber != null">
        #{agentPhonenumber,jdbcType=VARCHAR},
      </if>
      <if test="createTime != null">
        #{createTime,jdbcType=TIMESTAMP},
      </if>
      <if test="deleteStatus != null">
        #{deleteStatus,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>

不用过多的文字解释已经很清除了。
举一个例子:

前提Goods商品表里面有三个字段:id,name,price 
        1.此时我只设置了一个字段名字:  
        Goods g = new Goods();  
        g.setName("手机")insertSelective(g);
        insertSelective执行对应的sql语句的时候,只插入对应的name字段;
        (主键是自动添加的,默认插入为空)insert into tb_goods (id,name) value (null,"手机");
        注意:此时是没有price什么事的
        2、如果使用insert则是不论你设置多少个字段,统一都要添加一遍,不论你设置几个字段,即使是一个。
        Goods g=new Goods();
        g.setName("冰箱")insert(g)
        insert执行对应的sql语句的时候,统一都要添加一遍;
        insert into tb_goods (id,name,price) value (null,"冰箱",null)**注意:price也在哦!**  
        update  和  updateSelective 也一样的原理哦。。。。

你可能感兴趣的:(java,Java)