最近用到Springboot,配置了mybatis,在数据更新的时候忘了updateByPrimaryKeySelective和updateByPrimaryKey区别,在网上搜了一下,记录下来让自己加强记忆。
方法:
int updateByPrimaryKeySelective(User user);
int updateByPrimaryKey(User user);
对应的xml为:
<update id="updateByPrimaryKeySelective" parameterType="com.pingua.model.User">
update tb_user
<set>
<if test="name != null">
name= #{name,jdbcType=VARCHAR},
</if>
<if test="age != null">
age= #{age,jdbcType=INTEGER},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.pingua.model.User">
update tb_user
set name = #{name,jdbcType=VARCHAR},age = #{age,jdbcType=INTEGER},
where id = #{id,jdbcType=INTEGER}
</update>
updateByPrimaryKeySelective会先对字段进行判断再更新(如果为Null就忽略更新),如果你只想更新某一字段,可以用这个方法。
updateByPrimaryKey对你注入的字段全部更新
同时insert()方法和insertSelective()也是一样的原理