1. IKeyGenerator主键生成
内置实现类,缺少mysql,因为mysql不支持序列,只能通过表模拟序列
H2KeyGenerator
PostgreKeyGenerator
KingbaseKeyGenerator 人大金仓的KES数据库
DB2KeyGenerator
OracleKeyGenerator
2. 新建表模拟序列
CREATE TABLE `dual_sequence` (
`sequence_key` varchar(100) NOT NULL COMMENT '序列key(主键)',
`step` int NOT NULL DEFAULT '1' COMMENT '步长',
`start_value` bigint NOT NULL DEFAULT '0' COMMENT '开始值',
`end_value` bigint DEFAULT NULL COMMENT '结束值',
`ver` int DEFAULT NULL COMMENT '版本号',
PRIMARY KEY (`sequence_key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='临时序列表 '
--添加一条记录
INSERT INTO dual_sequence
(sequence_key, step, start_value, end_value, ver)
VALUES('next.dbid', 1, 0, NULL, 0);
3.代码实现
MysqlKeyGenerator类
package com.yl.mybatisplus.plugin;
import com.baomidou.mybatisplus.core.incrementer.IKeyGenerator;
import org.springframework.stereotype.Component;
@Component
public class MysqlKeyGenerator implements IKeyGenerator {
/**
* 执行sql
*
* @param incrementerName 序列名称
* @return
*/
@Override
public String executeSql(String incrementerName) {
String sql = "update dual_sequence set start_value=start_value+step where sequence_key='"+ incrementerName +"';" +
"select start_value as id from dual_sequence where sequence_key='" + incrementerName + "' for update;";
return sql;
}
}
实体类上添加@KeySequence,这里value是主键值,不是序列名
@Data
@TableName("luck_reward_emp")
@KeySequence(value = "next.dbid")
public class LuckRewardEmp {
@TableId(value = "id", type = IdType.INPUT)
private Long id;
}