MyBatis新增数据时自增id的两种写法小结

 更新时间:2024年09月27日 11:38:31   作者:惑边  
本文介绍了在MyBatis中配置自增ID的两种方法:一种是通过在Mapper文件中设置useGeneratedKeys和keyProperty,另一种是使用selectKey标签,批量插入时,同样采用useGeneratedKeys标签,感兴趣的可以了解一下

一、单个插入

  • 接口方法:
    public interface PlayerDao {
        int insertOnePlayer(Player player);
        int insertOnePlayer2(Player player);
    }

1.1 方式一

   public void testInsertGenerateId1() throws IOException {
           // 2.获取sqlSession
           SqlSession sqlSession = sqlSessionFactory.openSession();
           // 3.获取对应mapper
           PlayerDao mapper = sqlSession.getMapper(PlayerDao.class);
           // 4.执行查询语句并返回结果
           Player player = new Player();
           player.setPlayName("Allen Iverson");
           player.setPlayNo(3);
           player.setTeam("76ers");
           player.setHeight(1.83F);
           mapper.insertOnePlayer(player);
           sqlSession.commit();
           System.out.println(player.getId());
       }
  • Mapper文件:
      <insert id="insertOnePlayer" parameterType="Player" useGeneratedKeys="true" keyProperty="id">
     		insert into tb_player (id, playName, playNo,team, height)
     		values (
                 #{id,jdbcType=INTEGER},
                 #{playName,jdbcType=VARCHAR},
                 #{playNo,jdbcType=INTEGER},
                 #{team,jdbcType=VARCHAR},
                 #{height,jdbcType=DECIMAL}
     		)
     	</insert>
  • 方式一配置:useGeneratedKeys=“true” keyProperty=“id” 即可

1.2 方式二

    public void testInsertGenerateId2() throws IOException {
            // 2.获取sqlSession
            SqlSession sqlSession = sqlSessionFactory.openSession();
            // 3.获取对应mapper
            PlayerDao mapper = sqlSession.getMapper(PlayerDao.class);
            // 4.执行查询语句并返回结果
            Player player = new Player();
            player.setPlayName("Tony Parker");
            player.setPlayNo(9);
            player.setTeam("spurs");
            player.setHeight(1.88F);
            mapper.insertOnePlayer2(player);
            sqlSession.commit();
            System.out.println(player.getId());
        }
    
    
    Mapper文件:
   <insert id="insertOnePlayer2" parameterType="Player">
           <selectKey  keyProperty="id" order="AFTER" resultType="int">
               select LAST_INSERT_ID()
           </selectKey>
           insert into tb_player (id, playName, playNo,team, height)
           values (
           #{id,jdbcType=INTEGER},
           #{playName,jdbcType=VARCHAR},
           #{playNo,jdbcType=INTEGER},
           #{team,jdbcType=VARCHAR},
           #{height,jdbcType=DECIMAL}
           )
       </insert>
  • 方式二通过 selectKey 标签完成 ,selectKey 更加灵活,支持一定程度的自定义

二、批量插入

  • Java文件省略了,这里直接给出Mapper文件, Mapper 文件如下,其实就是:useGeneratedKeys=“true” keyProperty=“id”,其中id是JavaBean的主键id
  <insert id="insertBatch" parameterType="java.util.List" useGeneratedKeys="true" keyProperty="id">
   INSERT INTO partition_info (id, node_ip_id, init_schema_info_id,
   prefix_table_index, partition_num, start_time,
   end_time, create_time, is_delete
   )
   values
   <foreach collection="list" item="item" index="index" separator=",">
     (#{item.id,jdbcType=INTEGER}, #{item.nodeIpId,jdbcType=INTEGER}, #{item.initSchemaInfoId,jdbcType=INTEGER},
     #{item.prefixTableIndex,jdbcType=VARCHAR}, #{item.partitionNum,jdbcType=VARCHAR}, #{item.startTime,jdbcType=TIMESTAMP},
     #{item.endTime,jdbcType=TIMESTAMP}, #{item.createTime,jdbcType=TIMESTAMP}, #{item.isDelete,jdbcType=TINYINT}
     )
   </foreach>
 </insert>
  • Java代码
        System.out.println("before insert ...");
        for (PartitionInfo p: list) {
            System.out.println(p);
        }

        PartitionInfoMapper mapper = sqlSession.getMapper(PartitionInfoMapper.class);
        int i = mapper.insertBatch(list);
        System.out.println("The rows be affected :" + i);

        System.out.println("after insert ...");
        for (PartitionInfo p: list) {
            System.out.println(p);
        }
  • 输出

before insert ...
PartitionInfo(id=null, nodeIpId=1, initSchemaInfoId=1, prefixTableIndex=1, partitionNum=null, startTime=null, endTime=null, createTime=Fri Dec 13 18:26:46 CST 2019, isDelete=null)
PartitionInfo(id=null, nodeIpId=2, initSchemaInfoId=2, prefixTableIndex=2, partitionNum=null, startTime=null, endTime=null, createTime=Fri Dec 13 18:26:46 CST 2019, isDelete=null)
PartitionInfo(id=null, nodeIpId=3, initSchemaInfoId=3, prefixTableIndex=3, partitionNum=null, startTime=null, endTime=null, createTime=Fri Dec 13 18:26:46 CST 2019, isDelete=null)
The rows be affected :3
after insert ...
PartitionInfo(id=701, nodeIpId=1, initSchemaInfoId=1, prefixTableIndex=1, partitionNum=null, startTime=null, endTime=null, createTime=Fri Dec 13 18:26:46 CST 2019, isDelete=null)
PartitionInfo(id=702, nodeIpId=2, initSchemaInfoId=2, prefixTableIndex=2, partitionNum=null, startTime=null, endTime=null, createTime=Fri Dec 13 18:26:46 CST 2019, isDelete=null)
PartitionInfo(id=703, nodeIpId=3, initSchemaInfoId=3, prefixTableIndex=3, partitionNum=null, startTime=null, endTime=null, createTime=Fri Dec 13 18:26:46 CST 2019, isDelete=null) 

  • 这里其他的代码都省略了,基本上就是: useGeneratedKeys=“true” keyProperty=“id” 这两个标签起作用
  • 另外我用的mybatis版本是 3.4.1

三、注意

  • 注意Mapper文件中的 insert into tb_player (id, playName, playNo,team, height),这里不要多了一个逗号,之前height后面还有一个逗号导致一直空指针的错误。

 到此这篇关于MyBatis新增数据时自增id的两种写法小结的文章就介绍到这了,更多相关MyBatis新增数据时自增id内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Spring Cloud Gateway 服务网关的部署与使用详细讲解

    Spring Cloud Gateway 服务网关的部署与使用详细讲解

    这篇文章主要介绍了Spring Cloud Gateway 服务网关的部署与使用详细介绍,本文给大家讲解的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-04-04
  • Java代码性能测试实战之ContiPerf安装使用

    Java代码性能测试实战之ContiPerf安装使用

    这篇文章主要为大家介绍了Java代码性能测试实战之ContiPerf安装使用,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-06-06
  • 基于Java Gradle复制项目模块过程图解

    基于Java Gradle复制项目模块过程图解

    这篇文章主要介绍了基于Java Gradle复制项目模块过程图解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-06-06
  • springboot实现定时器(一看即会,非常简单)

    springboot实现定时器(一看即会,非常简单)

    这篇文章主要介绍了springboot实现定时器(一看即会,非常简单),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-12-12
  • Intellij IDEA Debug调试技巧(小结)

    Intellij IDEA Debug调试技巧(小结)

    这篇文章主要介绍了Intellij IDEA Debug调试技巧(小结),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-10-10
  • SpringBoot配置Redis连接池的实现步骤

    SpringBoot配置Redis连接池的实现步骤

    本文主要介绍了SpringBoot配置Redis连接池的实现步骤,详细的讲解了连接池的作用、配置方式、连接池参数说明,具有一定的参考价值,感兴趣的可以了解一下
    2025-03-03
  • Java之Swagger配置扫描接口以及开关案例讲解

    Java之Swagger配置扫描接口以及开关案例讲解

    这篇文章主要介绍了Java之Swagger配置扫描接口以及开关案例讲解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下
    2021-08-08
  • SpringBoot整合MQTT小结汇总

    SpringBoot整合MQTT小结汇总

    MQTT 客户端是运行 MQTT 库并通过网络连接到 MQTT 代理的任何设备,是一种基于发布/订阅(publish/subscribe)模式的“轻量级”通讯协议,该协议构建于 TCP/IP 协议上,由 IBM 于 1999 年发明,对SpringBoot整合MQTT相关知识感兴趣的朋友一起看看吧
    2022-01-01
  • 使用IDEA创建maven父子工程项目 (图文)

    使用IDEA创建maven父子工程项目 (图文)

    本文主要介绍了使用IDEA创建maven父子工程项目,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-04-04
  • Spring Boot应用监控的实战教程

    Spring Boot应用监控的实战教程

    Spring Boot 提供运行时的应用监控和管理功能,下面这篇文章主要给大家介绍了关于Spring Boot应用监控的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考借鉴,下面随着小编来一起学习学习吧
    2018-05-05

最新评论