自動(dòng)生成代碼insert和insertSelective的區(qū)別
自動(dòng)生成的mybatis對應(yīng)配置文件里面,有兩個(gè)方法拳氢,分別為insert和insertSelective。這兩個(gè)方法均是插入對象的方法放接。這里說一下兩者的區(qū)別栗恩。
首先看一下兩者代碼:
- insert
<insert id="insert" parameterType="com.cx.elearnning.model.SysSubject" >
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
-->
insert into sys_subject (SUBJECT_ID, SUBJECT_NAME, STATUS,
CREATE_TIME, PARENT_ID, sort
)
values (#{subjectId,jdbcType=INTEGER}, #{subjectName,jdbcType=VARCHAR}, #{status,jdbcType=BIT},
#{createTime,jdbcType=TIMESTAMP}, #{parentId,jdbcType=INTEGER}, #{sort,jdbcType=INTEGER}
)
</insert>
- insertSelective
<insert id="insertSelective" parameterType="com.cx.elearnning.model.SysSubject" >
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
-->
insert into sys_subject
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="subjectId != null" >
SUBJECT_ID,
</if>
<if test="subjectName != null" >
SUBJECT_NAME,
</if>
<if test="status != null" >
STATUS,
</if>
<if test="createTime != null" >
CREATE_TIME,
</if>
<if test="parentId != null" >
PARENT_ID,
</if>
<if test="sort != null" >
sort,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="subjectId != null" >
#{subjectId,jdbcType=INTEGER},
</if>
<if test="subjectName != null" >
#{subjectName,jdbcType=VARCHAR},
</if>
<if test="status != null" >
#{status,jdbcType=BIT},
</if>
<if test="createTime != null" >
#{createTime,jdbcType=TIMESTAMP},
</if>
<if test="parentId != null" >
#{parentId,jdbcType=INTEGER},
</if>
<if test="sort != null" >
#{sort,jdbcType=INTEGER},
</if>
</trim>
</insert>
分析
看完代碼大體上就能區(qū)分兩者的區(qū)別了吧磕秤?
insertSelective對應(yīng)的sql語句加入了NULL校驗(yàn)乳乌,即只會(huì)插入數(shù)據(jù)不為null的字段值市咆。
insert則會(huì)插入所有字段,會(huì)插入null磷瘤。
如何在執(zhí)行插入數(shù)據(jù)之后返回新增數(shù)據(jù)的ID(自增)
這里我們需要使用幾個(gè)屬性搜变,分別為:useGeneratedKeys采缚、keyColumn挠他、keyProperty。
上面所說的兩個(gè)插入方法贸呢,均不會(huì)返回新增數(shù)據(jù)的ID拢军。原因就是沒有配置這三個(gè)屬性楞陷。
配置方式
首先茉唉,需要配置useGeneratedKeys屬性结执,設(shè)置為true艾凯。說明將自動(dòng)生成的主鍵值進(jìn)行了獲取。
之后览芳,設(shè)置keyColumn(對應(yīng)數(shù)據(jù)表字段)、keyProperty(對應(yīng)對象屬性)沧竟。即將自動(dòng)生成的主鍵值賦值給那個(gè)屬性!
示例如下:
<insert id="createSubject" parameterType="com.cx.elearnning.model.SysSubject" useGeneratedKeys="true" keyColumn="SUBJECT_ID" keyProperty="subjectId">
INSERT INTO SYS_SUBJECT (
<include refid="sys_subject_columns" />
)
VALUES (
<include refid="sys_subject_properties" />
)
</insert>
表示將自增值賦值給了sunjectId屬性