一、添加数据返回该数据的主键
dao,entity,实体都不改变,只需要在mapper中加属性。
<insert id="replace" parameterType="参数类型"
useGeneratedKeys="true" keyProperty="pkid">
insert into 表名 (字段1,字段2)
values (对应值1,对应值2)
</insert>
useGeneratedKeys="true":给主键设置自增长
keyProperty="pkid" :将自增长后的主键赋值给实体类中的pkid
二、添加数据重复问题
当添加数据的时候难免会有重复,一般insert写法会报错:on duplicate key update
insert还有一种特殊的用法,出现重复的数据不报错,只是添加记录数为0
insert ignore into 表名(字段名1,字段名2) values(对应值1,对应值2);
三、官方文档-selectKey方式
官方文档原话:这里有一个简单(甚至很傻)的示例,它可以生成一个随机 ID(你最好不要这么做,但这里展示了 MyBatis 处理问题的灵活性及其所关心的广度)。
可以使用 select LAST_INSERT_ID() 来实现递增,从0开始
<insert id="insertAuthor">
<selectKey keyProperty="id" resultType="int" order="BEFORE">
select CAST(RANDOM()*1000000 as INTEGER) a from SYSIBM.SYSDUMMY1
/* select LAST_INSERT_ID() 从0开始滴 */
</selectKey>
insert into Author
(id, username, password, email,bio, favourite_section)
values
(#{id}, #{username}, #{password}, #{email}, #{bio}, #{favouriteSection,jdbcType=VARCHAR})
</insert>
四、多行插入
<insert id="insert" useGeneratedKeys="true"
keyProperty="实体对象标识(如果数据库和实体中的对象不一致,容易混淆)">
insert into Author (username, password, email, bio) values
<foreach item="item" collection="list" separator=",">
(#{item.username}, #{item.password}, #{item.email}, #{item.bio})
</foreach>
</insert>
dao层,@Param("list")对应这边的collection="list",item是循环的第一个对象
五、添加与更新同时存在--INSERT ... ON DUPLICATE KEY UPDATE语法
官网:语法官宣
<insert id="inserUpdate" parameterType="全类名" useGeneratedKeys="true" keyProperty="pkid">
insert into 表名
(字段Int,字段string,字段日期)
values
(#{pkid,jdbcType=INTEGER},#{linkUrl,jdbcType=VARCHAR},#{createDate,jdbcType=DATE})
ON DUPLICATE KEY UPDATE
update_user = #{对应类中的属性名,jdbcType=INTEGER},update_date = now(),
<if test="urlName != null and urlName != ''">url_name = #{类中的成员变量,jdbcType=VARCHAR},</if>
<if test="mTagId != null and mTagId != ''">m_tag_id = #{类中的属性名,jdbcType=VARCHAR}</if>
</insert>
也可以循环