MyBatis-Plus添加和主键策略
# 添加操作
// 测试添加
@Test
public void testAdd() {
User user = new User();
user.setName("无解");
user.setAge(20);
user.setEmail("12@qq.com");
int insert = userMapper.insert(user);
System.out.println(insert);
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4a5905d9] was not registered for synchronization because synchronization is not active
2022-02-17 22:32:54.289 INFO 21933 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2022-02-17 22:32:54.553 INFO 21933 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
JDBC Connection [HikariProxyConnection@180353207 wrapping com.mysql.cj.jdbc.ConnectionImpl@6d7cada5] will not be managed by Spring
==> Preparing: INSERT INTO user ( id, name, age, email ) VALUES ( ?, ?, ?, ? )
==> Parameters: 1494318945161748482(Long), 无解(String), 20(Integer), 12@qq.com(String)
<== Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4a5905d9]
1
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
可以看到有一个地方和别的不一样,就是我们的主键 id,我们并没有在设置对应的id
的值,是谁给我们添加的呢?是MP
的主键策略帮我们添加的。
# 主键策略
# ASSIGN_ID
MyBatis-Plus 默认的主键策略是:
ASSIGN_ID
(使用了雪花算法)
@TableId(type = IdType.ASSIGN_ID)
private String id;
1
2
2
雪花算法:分布式 ID 生成器,它能够保证不同的表的主键不重复,以及相同表的主键的有序性。
优点:整体上按照时间自增排序,并且整个分布式系统内不会产生 ID 碰撞,并且效率较高。
要想影响所有实体的配置,可以设置全局主键配置
# 全局设置主键生成策略
mybatis-plus.global-config.db-config.id-type=auto
1
2
2
编辑 (opens new window)
上次更新: 2022/02/17, 22:47:58