一次数据库主键莫名其妙的变得非常大排查记录
数据库中表结构是设置了主键自增,但是发现数据库中的id变成了这种1705604075022516225,然后怀疑是自增主键没有生效,反复尝试之后发现不是。因为手动插入数据的时候,主键是会自增的。于是把思路放在了排查mybatis-plus,之前一直用的mybatis,实体类中并没有显示的表明主键的生成方式,因为插入的时候主键会自动生成,以为mp也会这样。
这里说一下具体排查,可以直接在具体实体类的set方法中进行断点调试,然后在idea的debugger窗口中看一下调用步骤,然后可以直接回退到指定步骤,调试利器。
最后找到了这个地方
/**
* 自定义 ParameterHandler 重装构造函数,填充插入方法主键 ID
*
* @author nieqiuqiu 2020/6/5
* @since 3.4.0
*/
public class MybatisParameterHandler implements ParameterHandler {
}
protected void populateKeys(TableInfo tableInfo, MetaObject metaObject, Object entity) {
final IdType idType = tableInfo.getIdType();
final String keyProperty = tableInfo.getKeyProperty();
if (StringUtils.isNotBlank(keyProperty) && null != idType && idType.getKey() >= 3) {
//可以看到自动生成主键
final IdentifierGenerator identifierGenerator = GlobalConfigUtils.getGlobalConfig(this.configuration).getIdentifierGenerator();
Object idValue = metaObject.getValue(keyProperty);
if (identifierGenerator.assignId(idValue)) {
if (idType.getKey() == IdType.ASSIGN_ID.getKey()) {
Class> keyType = tableInfo.getKeyType();
if (Number.class.isAssignableFrom(keyType)) {
Number id = identifierGenerator.nextId(entity);
if (keyType == id.getClass()) {
metaObject.setValue(keyProperty, id);
} else if (Integer.class == keyType) {
metaObject.setValue(keyProperty, id.intValue());
} else if (Long.class == keyType) {
metaObject.setValue(keyProperty, id.longValue());
} else if (BigDecimal.class.isAssignableFrom(keyType)) {
metaObject.setValue(keyProperty, new BigDecimal(id.longValue()));
} else if (BigInteger.class.isAssignableFrom(keyType)) {
metaObject.setValue(keyProperty, new BigInteger(id.toString()));
} else {
throw new MybatisPlusException("Key type '" + keyType + "' not supported");
}
} else if (String.class.isAssignableFrom(keyType)) {
metaObject.setValue(keyProperty, identifierGenerator.nextId(entity).toString());
} else {
metaObject.setValue(keyProperty, identifierGenerator.nextId(entity));
}
} else if (idType.getKey() == IdType.ASSIGN_UUID.getKey()) {
metaObject.setValue(keyProperty, identifierGenerator.nextUUID(entity));
}
}
}
}
package com.baomidou.mybatisplus.core.config;
public static class DbConfig {
/**
* 主键类型
*/
private IdType idType = IdType.ASSIGN_ID;
}
默认是这个类型,这个类型mybatis-plus会自动生成主键。
package com.baomidou.mybatisplus.annotation;
public enum IdType {
AUTO(0),
NONE(1),
INPUT(2),
ASSIGN_ID(3),
ASSIGN_UUID(4);
}
@TableId(type = IdType.AUTO) 加上就好了