MyBatis在insert时返回自增长id值的方法

一、引言

在业务开发的时候,由于MyBatis框架的insert语句默认是不返回记录的主键值,而是返回插入的记录条数的,但是如果业务层需要得到插入数据的主键时候,可以通过配置的方式来实现获取插入数据的ID功能。

java 复制代码
 <!--
      useGeneratedKeys="true" 开启新增主键返回功能
      keyProperty="id" user实体主键属性
      keyColumn="id" user表中主键列
  -->
  <insert id="insertUser" parameterType="User" useGeneratedKeys="true" keyColumn="id" keyProperty="id">
     insert into user(username,password) values (#{username},#{password})
  </insert>

下面自己写的案例:

java代码中的Impl层(特别注意:此时DAO层就会将ID的值返回我们传参的实体类中):

java 复制代码
 @Override
    public ChatbotDomain insertChatbot(ChatbotDomain chatbotDomain) {
        chatbotDao.insertChatbot(chatbotDomain);
        // 此时 chatbotDomain.getId() 将会包含自增的 ID
        return chatbotDomain;
    }

DAO层:

java 复制代码
int insertChatbot(ChatbotDomain chatbotDomain);

mybatis中的XML文件:

XML 复制代码
<insert id="insertChatbot" parameterType="cn.jwis.qualitytool.bean.ChatbotDomain" useGeneratedKeys="true" keyColumn="id" keyProperty="id">
    INSERT INTO qcloud_pqm.chatbot_info
    (name, questions, answer, effective, supplementary_answers, create_date)
    VALUES( #{name}, #{questions}, #{answer}, #{effective}, #{supplementaryAnswers}, sysdate())
</insert>

***** java代码中的Impl层和XML尤为重*****

以上亲测有效,有不足请留言更新

相关推荐
RestCloud1 天前
SQL Server到Hive:批处理ETL性能提升30%的实战经验
数据库·api
RestCloud1 天前
为什么说零代码 ETL 是未来趋势?
数据库·api
ClouGence1 天前
CloudCanal + Paimon + SelectDB 从 0 到 1 构建实时湖仓
数据库
DemonAvenger1 天前
NoSQL与MySQL混合架构设计:从入门到实战的最佳实践
数据库·mysql·性能优化
AAA修煤气灶刘哥2 天前
后端人速藏!数据库PD建模避坑指南
数据库·后端·mysql
RestCloud2 天前
揭秘 CDC 技术:让数据库同步快人一步
数据库·api
得物技术2 天前
MySQL单表为何别超2000万行?揭秘B+树与16KB页的生死博弈|得物技术
数据库·后端·mysql
可涵不会debug2 天前
【IoTDB】时序数据库选型指南:工业大数据场景下的技术突围
数据库·时序数据库
ByteBlossom2 天前
MySQL 面试场景题之如何处理 BLOB 和CLOB 数据类型?
数据库·mysql·面试
麦兜*2 天前
MongoDB Atlas 云数据库实战:从零搭建全球多节点集群
java·数据库·spring boot·mongodb·spring·spring cloud