The method of auto-incrementing the table id

Several methods for auto-incrementing the database primary key id are listed as follows

1. Database self-increment (supported by some databases)
set id self-increment when creating a table, or modify table id self-increment later

# mysql 语法
create table your_table_name(
    id bigint(20)  not null auto_increment primary key comment '主键', // auto_increment 表示自增(固定死id从1开始,每次加1)
	name varchar(24) not null
);
# sqlserver 语法
create table [dbo].[your_table_name] (
  [id] int primary key identity(1,1) not null,// identity(1,1) 表示自增(支持id从N开始,每次加M,这里N,m都=1)
  [name] varchar(24) not null
);

2. Serial number (suitable for oracle)

# 创建序列号
create sequence user_seq
       minvalue 1  --最小值
       nomaxvalue --最大值
       start with 1 --起始值
       increment by 1  --增长基数
       nocycle  --不循环一直增加
       nocache ; -- 不使用缓存
       
# 插入数据       
insert into user (user_id, user_name, sex) values (user_seq.nextval, #{
    
    userName}, #{
    
    sex});

3. Mybatis acquires self-increment (general)
When the sql statement is executed, it will automatically bring the primary key field and filling value to execute, and there is no need to write the id field in the statement. The useGeneratedKeys attribute is false by default, keyProperty corresponds to the primary key id field name in the entity object, and keyColumn corresponds to the field name of the database

<insert id="addUser" parameterType="com.yulisao.User" useGeneratedKeys="true"
       keyProperty="userId" keyColumn="user_id">
    insert into user (user_name, sex) VALUES (#{
    
    userName}, #{
    
    sex})
</insert>

If it is sql in the form of annotation, it is written as follows

@Insert("<script>insert into user (user_name, sex) values (#{userName}, #{sex})</script>")
@Options(useGeneratedKeys=true, keyProperty="userId", keyColumn="user_id")
Integer addUser(User user);

Or customize the id value

<insert id="addUser" parameterType="com.yulisao.User" useGeneratedKeys="true"
            keyProperty="userId">
        <selectKey keyProperty="userId" resultType="int" order="BEFORE"> <!-- order 属性的值和数据库有关, mysql是 after,oracle是 before  -->
            <!-- 自己查询最后使用的id -->
            select isnull(max(user_id)+1, 1) as userId from user <!-- sqlserver语法-->
            <!-- select 你创建的序列名称.nextval from dual --><!-- oracle 查询最后使用的id -->
            <!-- select LAST_INSERT_ID() --><!-- mysql 查询最后使用的id -->
            <!-- select SCOPE_IDENTITY() --><!-- sqlserver 查询最后的id -->
        </selectKey>
        insert into user (user_name, sex) values (#{
    
    userName}, #{
    
    sex});
    </insert>

expand knowledge

  1. <insert>The tag contains attributes as follows
  • id : unique identifier, the id of each sql statement is different, if there are repeated startup projects, an error should be reported
  • parameterType: The class name or alias of the input parameter is optional (MyBatis can automatically infer the input parameter type)
  • resultType : the class name or alias of the returned result
  • flushCache: The default value is true, and any execution will clear the first-level cache and the second-level cache
  • timeout : timeout time in seconds
  • statementType : For STATEMENT, PREPARED, and ALLABLE, MyBatis will use the corresponding Statement, PreparedStatement, and Callable statement respectively, and the default is PREPARED
  • useGeneratedKeys: The default value is false. If set to true, MyBatis uses the JDBC - getGeneratedKeys method to retrieve the primary key generated internally by the database
  • keyProperty: Which field name will be assigned to the primary key id value obtained by MyBatis through getGeneratedKeys (that is, the camel case userId in the entity object)
  • keyColumn: only valid for insert, what is the generated column name (that is, the underlined field name user_id of the database table) must be related to the database type, for example, PostgreSQL must
  • databaseId : This attribute is only used when a project uses multiple databases/data sources. If databaseIdProvider is configured, MyBatis will load all statements without databaseId or matching the current databaseId; if there are statements with or without, the ones without will be ignored. That is, if the databaseIdProvider is not configured in the mybatis configuration file, the databaseId attribute will not take effect.

More attributes, and attributes of other tags can be seen here (from XXXMapper.xml, press and hold ctrl to click on the tag or attribute to jump in). Sometimes the
insert image description here
useGeneratedKeys attribute is used but it does not take effect. You can also refer to the following reasons

  • Set keyProperty, the value of keyColumn is incorrect
  • The id field of the database must be set to auto-increment
  • If the input parameter is modified with @Param, the id cannot be automatically assigned

Finally, it is not recommended to implement id auto-increment through triggers, events, etc., so I won’t give an example.

Guess you like

Origin blog.csdn.net/qq_29539827/article/details/130105579