SoFunction
Updated on 2025-03-02

Summary of two ways to write about self-increase id when MyBatis adds new data

1. Single insertion

  • Interface method:
    public interface PlayerDao {
        int insertOnePlayer(Player player);
        int insertOnePlayer2(Player player);
    }

1.1 Method 1

   public void testInsertGenerateId1() throws IOException {
           // 2. Get sqlSession           SqlSession sqlSession = ();
           // 3. Get the corresponding mapper           PlayerDao mapper = ();
           // 4. Execute the query statement and return the result           Player player = new Player();
           ("Allen Iverson");
           (3);
           ("76ers");
           (1.83F);
           (player);
           ();
           (());
       }
  • Mapper file:
      <insert  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>
  • Method 1 configuration: useGeneratedKeys="true" keyProperty="id"

1.2 Method 2

    public void testInsertGenerateId2() throws IOException {
            // 2. Get sqlSession            SqlSession sqlSession = ();
            // 3. Get the corresponding mapper            PlayerDao mapper = ();
            // 4. Execute the query statement and return the result            Player player = new Player();
            ("Tony Parker");
            (9);
            ("spurs");
            (1.88F);
            mapper.insertOnePlayer2(player);
            ();
            (());
        }
    
    
    Mapperdocument:
   &lt;insert  parameterType="Player"&gt;
           &lt;selectKey  keyProperty="id" order="AFTER" resultType="int"&gt;
               select LAST_INSERT_ID()
           &lt;/selectKey&gt;
           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}
           )
       &lt;/insert&gt;
  • Method 2 is completed through the selectKey tag. SelectKey is more flexible and supports a certain degree of customization.

2. Batch insertion

  • The Java file is omitted, and the Mapper file is directly given here. The Mapper file is as follows, which is actually: useGeneratedKeys="true" keyProperty="id", where id is the primary key id of JavaBean
  <insert  parameterType="" 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=",">
     (#{,jdbcType=INTEGER}, #{,jdbcType=INTEGER}, #{,jdbcType=INTEGER},
     #{,jdbcType=VARCHAR}, #{,jdbcType=VARCHAR}, #{,jdbcType=TIMESTAMP},
     #{,jdbcType=TIMESTAMP}, #{,jdbcType=TIMESTAMP}, #{,jdbcType=TINYINT}
     )
   </foreach>
 </insert>
  • Java code
        ("before insert ...");
        for (PartitionInfo p: list) {
            (p);
        }

        PartitionInfoMapper mapper = ();
        int i = (list);
        ("The rows be affected :" + i);

        ("after insert ...");
        for (PartitionInfo p: list) {
            (p);
        }
  • Output

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) 

  • All other codes here are omitted, basically: useGeneratedKeys="true" keyProperty="id" These two tags work
  • In addition, the version of mybatis I use is 3.4.1

3. Pay attention

  • Note the insert into tb_player (id, playName, playNo, team, height) in the Mapper file. Don't add a comma here. There is a comma after the height before, which causes the pointer to be null.

This is the article about the two ways to write about the self-increase id when MyBatis adds new data. This is the end of this article. For more related content about the self-increase id when MyBatis adds new data, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!