MyBatis插入Insert、InsertSelective的区别及使用心得
这篇文章主要介绍了MyBatis插入Insert、InsertSelective的区别及使用心得,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
目录
逆向自动生成的mybatis对应配置Mapper文件里面,有两个方法,分别为insert和insertSelective。这两个方法均是插入对象的方法。为什么会有两个插入方法呢?这里说一下两者的区别。
首先我们看代码如下:
insert方法
1 2 3 4 5 6 7 8 9 10 | < insert id= "insert" parameterType= "demo.pojo.domain.HspMediaInf" > insert into MEDIA_INF (MED_SEQ, EMG_SEQ, MED_CLASS, MED_NAME, MED_FILE, MED_EXTEND, MED_TYPE, MED_DATE, MED_SIZE, MED_DATA) values (#{medSeq,jdbcType= VARCHAR }, #{emgSeq,jdbcType= VARCHAR }, #{medClass,jdbcType= VARCHAR }, #{medName,jdbcType= VARCHAR }, #{medFile,jdbcType= VARCHAR }, #{medExtend,jdbcType= VARCHAR }, #{medType,jdbcType= VARCHAR }, #{medDate,jdbcType= TIMESTAMP }, #{medSize,jdbcType= DECIMAL }, #{medData,jdbcType=BLOB}) </ insert > |
insertSelective方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | < insert id= "insertSelective" parameterType= "activetech.zyyhospital.pojo.domain.HspMediaInf" > insert into HSP_MEDIA_INF <trim prefix= "(" suffix= ")" suffixOverrides= "," > <if test= "medSeq != null" > MED_SEQ, </if> <if test= "emgSeq != null" > EMG_SEQ, </if> <if test= "medClass != null" > MED_CLASS, </if> <if test= "medName != null" > MED_NAME, </if> <if test= "medFile != null" > MED_FILE, </if> <if test= "medExtend != null" > MED_EXTEND, </if> <if test= "medType != null" > MED_TYPE, </if> <if test= "medDate != null" > MED_DATE, </if> <if test= "medSize != null" > MED_SIZE, </if> <if test= "medData != null" > MED_DATA, </if> </trim> <trim prefix= "values (" suffix= ")" suffixOverrides= "," > <if test= "medSeq != null" > #{medSeq,jdbcType= VARCHAR }, </if> <if test= "emgSeq != null" > #{emgSeq,jdbcType= VARCHAR }, </if> <if test= "medClass != null" > #{medClass,jdbcType= VARCHAR }, </if> <if test= "medName != null" > #{medName,jdbcType= VARCHAR }, </if> <if test= "medFile != null" > #{medFile,jdbcType= VARCHAR }, </if> <if test= "medExtend != null" > #{medExtend,jdbcType= VARCHAR }, </if> <if test= "medType != null" > #{medType,jdbcType= VARCHAR }, </if> <if test= "medDate != null" > #{medDate,jdbcType= TIMESTAMP }, </if> <if test= "medSize != null" > #{medSize,jdbcType= DECIMAL }, </if> <if test= "medData != null" > #{medData,jdbcType=BLOB}, </if> </trim> </ insert > |
从上面连段代码我们会发现insertSelective对应的sql语句加入了NULL校验,只会插入数据不为null的字段值。insert则会插入所有字段,会插入null。
笔者反思但是为什么会有这两种方法呢?
总结:由于真实开发中,我们在修改功能的from表单,或者一个类的某些模块编辑的from表单中不会将所有的数据都查询出来放到from表单中然后再insert到数据库,所以我们经常在这些功能中使用insertSelective方法,此时只针对我们操作的属性进行insert操作,而如果使用insert方法,将会把非表单内的内容置为null从而影响数据安全。
原文链接:https://blog.csdn.net/huluwa10526/article/details/90232350