MyBatis insert操作插入数据之后返回插入记录的id

2025-05-29 0 79

mybatis插入数据的时候,返回该记录的id

?

1

2

3

4

5
<insert id="insert"

keyproperty="id"

usegeneratedkeys="true"
 parametertype="com.demo.domain.countrateconfig">


insert into query_rate_config (code,partner_type,search_count, booking_count, ticket_count,rate_type)


values (#{code,jdbctype=varchar},#{partnertype,jdbctype=tinyint}, #{searchcount,jdbctype=integer},
 #{bookingcount,jdbctype=integer}, #{ticketcount,jdbctype=integer},#{ratetype,jdbctype=tinyint})
</insert>

首先我们应该保证数据库的主键id是自增的,另外需要设置的两个属性为:

keyproperty="id"
usegeneratedkeys="true"


这样的话,我们在插入数据之后,就可以得到插入数据之后的对象,然后通过该对象获取该对象的id。

usegeneratedkeys=”true” 可以获取自增长的id 只支持具有自增长方式的那种数据库(mysql, mssql 等 但 oracle 就不支持了 )

案例如下:

1、mybatis的配置文件如上遍所示的一段代码;

2、使用的java代码如下:

?

1

2

3

4

5

6
@override

public int insert(countrateconfig countrateconfig) {

int insertnum = integer.parseint(countrateconfigmapper.insert(countrateconfig) + "");

long id = countrateconfig.getid();

return insertnum;

}

3、上述代码,如果插入数据成功的话,则可以找到数据库中对应的key;

结果是正确的,即可以读取正确的id。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对快网idc的支持。如果你想了解更多相关内容请查看下面相关链接

原文链接:https://blog.csdn.net/xlgen157387/article/details/49130803

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 MyBatis insert操作插入数据之后返回插入记录的id https://www.kuaiidc.com/109342.html

相关文章

发表评论
暂无评论