MyBatis-Plus Insert Testing and Snowflake Algorithm
Insert Testing
/*
* Insert test
*/
@Test
public void testInsert() {
User user = new User();
/*
* ID is automatically generated
*/
user.setName("kuku");
user.setAge(3);
user.setEmail("2983394967@qq.com");
int rows = mapper.insert(user);
System.out.println(rows);
/*
* The ID is automatically populated back
*/
System.out.println(user);
}
Note that the database table does not have an ID column set.
Snowflake Algorithm (Default ID Generation)
The Snowflake algorithm is a distributed ID generation algorithm open-sourced by Twitter. It produces a long type ID. The core idea is:
- 41 bits for milliseconds
- 10 bits for machine ID (5 bits for data center — e.g., Beijing, Shanghai — and 5 bits for machine)
- 12 bits for sequence within a millisecond (each node can generate 4096 IDs per millisecond)
- 1 sign bit, always 0
For the reference implementation, see: https://github.com/twitter/snowflake. The Snowflake algorithm can support approximately 4.19 million TPS (2^22 * 1000).
MyBatis-Plus Primary Key Strateiges
AUTO(0), // Auto-increment, requires database auto-increment configured
NONE(1), // No primary key type set
INPUT(2), // User input, consistent with database type
ASSIGN_ID(3), // Snowflake algorithm, globally unique ID, database field must be numeric
ASSIGN_UUID(4); // Globally unique UUID
Note: In newer versions of MyBatis-Plus, the default primary key strategy is NONE, which correpsonds to the Snowflake algorithm. The ID_WORKER_STR(5) strategy has been removed.
Entity Class Example
Use @TableId(type = IdType.AUTO) on the primary key field and adjust the type as needed.
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
@TableId(type = IdType.AUTO)
private Long id; // Must be Long (wrapper class) for automatic generation
private String name;
private int age;
private String email;
}
Configuration via Properties File
# Configure auto-increment globally
mybatis-plus.global-config.db-config.id-type=auto