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

作者简介:大家好,我是smart哥,前中兴通讯、美团架构师,现某互联网公司CTO

联系qq:184480602,加我进群,大家一起学习,一起进步,一起对抗互联网寒冬

学习必须往深处挖,挖的越深,基础越扎实!

阶段1、深入多线程

阶段2、深入多线程设计模式

阶段3、深入juc源码解析


阶段4、深入jdk其余源码解析


阶段5、深入jvm源码解析

码哥源码部分

码哥讲源码-原理源码篇【2024年最新大厂关于线程池使用的场景题】

码哥讲源码【炸雷啦!炸雷啦!黄光头他终于跑路啦!】

码哥讲源码-【jvm课程前置知识及c/c++调试环境搭建】

​​​​​​码哥讲源码-原理源码篇【揭秘join方法的唤醒本质上决定于jvm的底层析构函数】

码哥源码-原理源码篇【Doug Lea为什么要将成员变量赋值给局部变量后再操作?】

码哥讲源码【你水不是你的错,但是你胡说八道就是你不对了!】

码哥讲源码【谁再说Spring不支持多线程事务,你给我抽他!】

终结B站没人能讲清楚红黑树的历史,不服等你来踢馆!

打脸系列【020-3小时讲解MESI协议和volatile之间的关系,那些将x86下的验证结果当作最终结果的水货们请闭嘴】

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

一、单个插入

  • 接口方法:
        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后面还有一个逗号导致一直空指针的错误。
  • 9
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值