mybatis执行insert语句后,返回当前插入数据主键的方法

实际开发中,有时候需要把当前插入的数据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>

 

  • 5
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值