insert和insertSelective区别

两者的区别在于如果选择insert 那么所有的字段都会添加一遍即使没有值

 <insert id="insert" parameterType="com.ego.pojo.TbContentCategory" >
    insert into tb_content_category (id, parent_id, name, 
      status, sort_order, is_parent, 
      created, updated)
    values (#{id,jdbcType=BIGINT}, #{parentId,jdbcType=BIGINT}, #{name,jdbcType=VARCHAR}, 
      #{status,jdbcType=INTEGER}, #{sortOrder,jdbcType=INTEGER}, #{isParent,jdbcType=BIT}, 
      #{created,jdbcType=TIMESTAMP}, #{updated,jdbcType=TIMESTAMP})
  </insert>

 


 

但是如果使用inserSelective就会只给有值的字段赋值(会对传进来的值做非空判断)

<insert id="insertSelective" parameterType="com.ego.pojo.TbContentCategory" >
    insert into tb_content_category
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="parentId != null" >
        parent_id,
      </if>
      <if test="name != null" >
        name,
      </if>
      <if test="status != null" >
        status,
      </if>
      <if test="sortOrder != null" >
        sort_order,
      </if>
      <if test="isParent != null" >
        is_parent,
      </if>
      <if test="created != null" >
        created,
      </if>
      <if test="updated != null" >
        updated,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=BIGINT},
      </if>
      <if test="parentId != null" >
        #{parentId,jdbcType=BIGINT},
      </if>
      <if test="name != null" >
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="status != null" >
        #{status,jdbcType=INTEGER},
      </if>
      <if test="sortOrder != null" >
        #{sortOrder,jdbcType=INTEGER},
      </if>
      <if test="isParent != null" >
        #{isParent,jdbcType=BIT},
      </if>
      <if test="created != null" >
        #{created,jdbcType=TIMESTAMP},
      </if>
      <if test="updated != null" >
        #{updated,jdbcType=TIMESTAMP},
      </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也在哦!!

  


insert和insertSelective插入数据库后,在数据库中的效果是一样的,只是sql语句不同。

 


 

insert和insertSelective

insert就是把所有值插入,此时数据库中有default值,default值就不起作用了

insertSelective不会忽略default值。

 

posted @ 2019-07-29 23:26  Roy-Xin  阅读(3954)  评论(0编辑  收藏  举报