兩者的區別在於如果選擇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值。