插入方法跟踪
跟随mybatis-plus的insert或者save方法,可以查阅到插入的id设置策略(假设未手动设置id):
MybatisDefaultParameterHandler.java
//ASSIGN_ID是雪花算法策略
protected static 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(tableInfo.getConfiguration()).getIdentifierGenerator();
Object idValue = metaObject.getValue(keyProperty);
if (StringUtils.checkValNull(idValue)) {
if (idType.getKey() == IdType.ASSIGN_ID.getKey()) {
if (Number.class.isAssignableFrom(tableInfo.getKeyType())) {
metaObject.setValue(keyProperty, identifierGenerator.nextId(entity));
} else {
metaObject.setValue(keyProperty, identifierGenerator.nextId(entity).toString());
}
} else if (idType.getKey() == IdType.ASSIGN_UUID.getKey()) {
metaObject.setValue(keyProperty, identifierGenerator.nextUUID(entity));
}
}
}
}
未手动设置id策略,为什么插入到数据库却是雪花算法生成的id?
项目启动时需要注入mybatisplus的一些bean,执行了方法:MybatisSqlSessionFactoryBuilder.build(Configuration config)
代码如下:
// TODO 使用自己的逻辑,注入必须组件
@Override
public SqlSessionFactory build(Configuration config) {
MybatisConfiguration configuration = (MybatisConfiguration) config;
GlobalConfig globalConfig = GlobalConfigUtils.getGlobalConfig(configuration);
final IdentifierGenerator identifierGenerator;
if (globalConfig.getIdentifierGenerator() == null) {
if (null != globalConfig.getWorkerId() && null != globalConfig.getDatacenterId()) {
identifierGenerator = new DefaultIdentifierGenerator(globalConfig.getWorkerId(), globalConfig.getDatacenterId());
} else {
//默认执行这里
identifierGenerator = new DefaultIdentifierGenerator();
}
globalConfig.setIdentifierGenerator(identifierGenerator);
} else {
identifierGenerator = globalConfig.getIdentifierGenerator();
}
//TODO 这里只是为了兼容下,并没多大重要,方法标记过时了.
IdWorker.setIdentifierGenerator(identifierGenerator);
if (globalConfig.isEnableSqlRunner()) {
new SqlRunnerInjector().inject(configuration);
}
SqlSessionFactory sqlSessionFactory = super.build(configuration);
// 缓存 sqlSessionFactory
globalConfig.setSqlSessionFactory(sqlSessionFactory);
return sqlSessionFactory;
}
默认情况下,调试执行代码:
identifierGenerator = new DefaultIdentifierGenerator();
即SqlSessionFactory默认使用雪花算法,globalConfig全局配置默认为雪花算法