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类文章来源:https://www.toymoban.com/news/detail-637337.html
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是主键值,不是序列名文章来源地址https://www.toymoban.com/news/detail-637337.html
@Data
@TableName("luck_reward_emp")
@KeySequence(value = "next.dbid")
public class LuckRewardEmp {
@TableId(value = "id", type = IdType.INPUT)
private Long id;
}
到了这里,关于mybatis-plus实现mysql自定义IKeyGenerator的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!