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内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 浅谈Java安全之C3P0的使用

    浅谈Java安全之C3P0的使用

    本文主要介绍了浅谈Java安全之C3P0的使用,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-01-01
  • dubbo转http方式调用方式

    dubbo转http方式调用方式

    当前项目计划去掉网关层,前端将直接通过HTTP调用后端dubbo服务,为此,后端需新增controller层,实现请求兼容和统一转发,保证前端调用方式不变
    2025-10-10
  • Java之map的常见用法讲解与五种循环遍历实例代码理解

    Java之map的常见用法讲解与五种循环遍历实例代码理解

    map是一组键值对的组合,通俗理解类似一种特殊的数组,a[key]=val,只不过数组元素的下标是任意一种类型,而且数组的元素的值也是任意一种类型。有点类似python中的字典。通过"键"来取值,类似生活中的字典,已知索引,来查看对应的信息
    2021-09-09
  • IDEA之web项目导入jar包方式

    IDEA之web项目导入jar包方式

    这篇文章主要介绍了IDEA之web项目导入jar包方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-05-05
  • Springboot 如何使用@Async整合线程池

    Springboot 如何使用@Async整合线程池

    这篇文章主要介绍了Springboot 使用@Async整合线程池的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-06-06
  • myatisplus的saveOrUpdate的提交总是update问题

    myatisplus的saveOrUpdate的提交总是update问题

    这篇文章主要介绍了myatisplus的saveOrUpdate的提交总是update问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-11-11
  • 浅谈Spring自定义注解从入门到精通

    浅谈Spring自定义注解从入门到精通

    这篇文章主要介绍了浅谈Spring自定义注解从入门到精通,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-09-09
  • 详解mybatis 批量更新数据两种方法效率对比

    详解mybatis 批量更新数据两种方法效率对比

    这篇文章主要介绍了详解mybatis 批量更新数据两种方法效率对比,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-02-02
  • Java微服务分布式调度Elastic-job环境搭建及配置

    Java微服务分布式调度Elastic-job环境搭建及配置

    Elastic-Job在配置中提供了JobEventConfiguration,支持数据库方式配置,会在数据库中自动创建JOB_EXECUTION_LOG和JOB_STATUS_TRACE_LOG两张表以及若干索引,来记录作业的相关信息
    2023-02-02
  • SSH框架网上商城项目第15战之线程、定时器同步首页数据

    SSH框架网上商城项目第15战之线程、定时器同步首页数据

    这篇文章主要为大家详细介绍了SSH框架网上商城项目第15战之线程、定时器同步首页数据,感兴趣的小伙伴们可以参考一下
    2016-06-06

最新评论