实际开发中,有时候需要把当前插入的数据id取出来,但又不想再去查一遍.
1.mybatis提供了两种返回insert方法后的主键的方法 :
第一种方法:根据useGeneratedKeys获取返回值, 部分数据库不支持
<insert id="insertUser" useGeneratedKeys="true" keyProperty="id" parameterType="com.entity.user">
insert into test (name) values (#{name})
</insert>
useGeneratedKeys="true": 设置是否使用JDBC的getGeneratedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中.
keyProperty: 赋值的对象属性名称.
添加完成后, 直接根据对象属性取id. xxx.getID()
第二种方法:根据selectKey获取
<insert id="saveServerAddress" parameterType="com.xxl.job.admin.core.model.ServerControl">
<selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="id">
SELECT LAST_INSERT_ID()
</selectKey>
INSERT INTO
XXL_JOB_SERVER_CONTROL
(server)
VALUES
(#{serverAddress});
order属性, 指定是在insert语句前还是后执行selectKey操作,
xxx.getID()
2.解决bug:insertBatch批量插入后无法获取id
Could not determine which parameter to assign generated keys to. Note that when there are multiple parameters, 'keyProperty' must include the parameter name (e.g. 'param.id'). Specified key properties are [id] and available parameters are [list, param1, tableName, param2]
insertBatch批量插入时,由于需要确定生成的键分配给到哪个参数,如果想要获取到list数据主键id,keyProperty需要指向list的id;
解决方法:
useGeneratedKeys="true" keyProperty="list.id"
<insert id="insertBatch" useGeneratedKeys="true" keyProperty="list.id" parameterType="cn.xxx.HisFlow">
INSERT INTO public."${tableName}" (...)
VALUES
<foreach collection="list" item="item" index="index" separator=",">
....
</foreach>
</insert>