本文源码:Gitee·点这里
使用主键注解@TableId
,加到pojo类的主键上
属性 | 类型 | 必须指定 | 默认值 | 描述 |
---|---|---|---|---|
value | String | 否 | "" | 主键字段名 |
type | Enum | 否 | IdType.NONE | 主键类型 |
IdType
值 | 描述 |
---|---|
AUTO | 数据库ID自增 |
NONE | 无状态,该类型为未设置主键类型(注解里等于跟随全局,全局里约等于 INPUT) |
INPUT | insert前自行set主键值 |
ASSIGN_ID | 分配ID(主键类型为Number(Long和Integer)或String)(since 3.3.0),使用接口IdentifierGenerator 的方法nextId (默认实现类为DefaultIdentifierGenerator 雪花算法) |
ASSIGN_UUID | 分配UUID,主键类型为String(since 3.3.0),使用接口IdentifierGenerator 的方法nextUUID (默认default方法) |
ID_WORKER | 分布式全局唯一ID 长整型类型(please use ASSIGN_ID ) |
UUID | 32位UUID字符串(please use ASSIGN_UUID ) |
ID_WORKER_STR | 分布式全局唯一ID 字符串类型(please use ASSIGN_ID ) |
数据库自增主键 - AUTO
插入时不会带ID列,需要数据库设置ID自增
插入日志:
JDBC Connection [HikariProxyConnection@1681215776 wrapping com.mysql.cj.jdbc.ConnectionImpl@64b7225f] will not be managed by Spring
==> Preparing: INSERT INTO user ( name, age, email ) VALUES ( ?, ?, ? )
==> Parameters: Mimi(String), 19(Integer), [email protected](String)
<== Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@2a389173]
用户输入 - INPUT
insert前自行set主键值
插入日志:
JDBC Connection [HikariProxyConnection@952288009 wrapping com.mysql.cj.jdbc.ConnectionImpl@1a480135] will not be managed by Spring
==> Preparing: INSERT INTO user ( id, name, age, email ) VALUES ( ?, ?, ?, ? )
==> Parameters: 9(Long), Mimi(String), 19(Integer), [email protected](String)
<== Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@70e02081]
无状态 - NONE
未设置主键类型,类似于ASSIGN_ID
插入日志:
JDBC Connection [HikariProxyConnection@79620878 wrapping com.mysql.cj.jdbc.ConnectionImpl@6e8a9c30] will not be managed by Spring
==> Preparing: INSERT INTO user ( id, name, age, email ) VALUES ( ?, ?, ?, ? )
==> Parameters: 1307978008895885313(Long), Mimi(String), 19(Integer), [email protected](String)
<== Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7573e12f]
分配ID - ASSIGN_ID
默认使用插入对象ID,当插入对象ID为空时,使用雪花算法
雪花算法结构图:
插入日志:
JDBC Connection [HikariProxyConnection@79620878 wrapping com.mysql.cj.jdbc.ConnectionImpl@6e8a9c30] will not be managed by Spring
==> Preparing: INSERT INTO user ( id, name, age, email ) VALUES ( ?, ?, ?, ? )
==> Parameters: 1307978926462754817(Long), Mimi(String), 19(Integer), [email protected](String)
<== Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7573e12f]
分配UUID - ASSIGN_UUID
默认使用插入对象ID,当插入对象ID为空时,使用UUID,并去除“-”,主键类型为String
插入日志:
JDBC Connection [HikariProxyConnection@81355344 wrapping com.mysql.cj.jdbc.ConnectionImpl@9a6fbc0] will not be managed by Spring
==> Preparing: INSERT INTO dept ( id, name ) VALUES ( ?, ? )
==> Parameters: 4b0e878b5bfc2f22f44f1a3691403116(String), 研发部(String)
<== Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4ae263bf]
1