版权声明:转载请注明原创地址 https://blog.csdn.net/ke369093457/article/details/82851927
有时候当一条记录插入之后,需要用到当前记录的id,
方法有二:
一:插入当前记录之后,在根据条件去表中查询;
二:插入记录时直接返回主键;
第一种方法就不说了,我就说说第二种方法:
<insert id="insert" useGeneratedKeys="true" keyProperty="id">
INSERT
INTO ke_pack_send(
id,
device_id,
content,
grade,
flag,
update_time,
mark,mark_name
) VALUES (
#{id},
#{deviceId},
#{content},
#{grade},
#{flag},
#{updateTime},
#{mark},
#{markName}
)
</insert>
注:
1、添加记录能够返回主键的关键点在于需要在<insert>标签中添加以下三个属性<insert useGeneratedKeys="true" keyProperty="id" keyColumn="id"></insert>。
useGeneratedKeys:必须设置为true,否则无法获取到主键id。
keyProperty:设置为POJO对象的主键id属性名称。
keyColumn:设置为数据库记录的主键id字段名称
2、新添加主键id并不是在执行添加操作时直接返回的,而是在执行添加操作之后将新添加记录的主键id字段设置为POJO对象的主键id属性
useGeneratedKeys设置为true,keyProperty设置为主键对应实体类的属性值,如果是联合主键那么属性名用逗号隔开;insert时,返回的是新增记录的主键值、update时返回的时更新记录的主键值;
但是在插入时如果出现主键冲突,此方法经测试是无效的。
<insert id="insert" useGeneratedKeys="true" keyProperty="id">
INSERT
INTO village(
city,
area,
village,
company_id,
office_id,
type,
create_by
)
VALUES (
#{city},
#{area},
#{village},
#{companyId},
#{officeId},
#{type},
#{createBy.id}
)ON
DUPLICATE KEY
UPDATE no=no
</insert>
此时是没办法返回到主键的。
但是可以使用以下方法:
<insert id="insertUserOffice">
<selectKey keyProperty='no' resultType='java.lang.String'
order='AFTER'>
SELECT
no
FROM user
WHERE phone = #{phone}
</selectKey>
INSERT INTO user(
name,
phone,
card
) VALUES (
#{name},
#{phone},
#{card}
)on duplicate
key
update
name = #{name}
</insert>
参数属性:
属性名 | 作用 |
resultType | selectKey指定sql返回值类型 |
order | 执行顺序,after,表示后执行,before,表示先执行 |
keyProperty | 主键对应实体类中的属性名字 |