插入方法跟踪

跟随mybatis-plus的insert或者save方法,可以查阅到插入的id设置策略(假设未手动设置id):
MybatisDefaultParameterHandler.java

  1. //ASSIGN_ID是雪花算法策略
  2. protected static void populateKeys(TableInfo tableInfo, MetaObject metaObject, Object entity) {
  3. final IdType idType = tableInfo.getIdType();
  4. final String keyProperty = tableInfo.getKeyProperty();
  5. if (StringUtils.isNotBlank(keyProperty) && null != idType && idType.getKey() >= 3) {
  6. final IdentifierGenerator identifierGenerator = GlobalConfigUtils.getGlobalConfig(tableInfo.getConfiguration()).getIdentifierGenerator();
  7. Object idValue = metaObject.getValue(keyProperty);
  8. if (StringUtils.checkValNull(idValue)) {
  9. if (idType.getKey() == IdType.ASSIGN_ID.getKey()) {
  10. if (Number.class.isAssignableFrom(tableInfo.getKeyType())) {
  11. metaObject.setValue(keyProperty, identifierGenerator.nextId(entity));
  12. } else {
  13. metaObject.setValue(keyProperty, identifierGenerator.nextId(entity).toString());
  14. }
  15. } else if (idType.getKey() == IdType.ASSIGN_UUID.getKey()) {
  16. metaObject.setValue(keyProperty, identifierGenerator.nextUUID(entity));
  17. }
  18. }
  19. }
  20. }

未手动设置id策略,为什么插入到数据库却是雪花算法生成的id?

项目启动时需要注入mybatisplus的一些bean,执行了方法:MybatisSqlSessionFactoryBuilder.build(Configuration config)
代码如下:

  1. // TODO 使用自己的逻辑,注入必须组件
  2. @Override
  3. public SqlSessionFactory build(Configuration config) {
  4. MybatisConfiguration configuration = (MybatisConfiguration) config;
  5. GlobalConfig globalConfig = GlobalConfigUtils.getGlobalConfig(configuration);
  6. final IdentifierGenerator identifierGenerator;
  7. if (globalConfig.getIdentifierGenerator() == null) {
  8. if (null != globalConfig.getWorkerId() && null != globalConfig.getDatacenterId()) {
  9. identifierGenerator = new DefaultIdentifierGenerator(globalConfig.getWorkerId(), globalConfig.getDatacenterId());
  10. } else {
  11. //默认执行这里
  12. identifierGenerator = new DefaultIdentifierGenerator();
  13. }
  14. globalConfig.setIdentifierGenerator(identifierGenerator);
  15. } else {
  16. identifierGenerator = globalConfig.getIdentifierGenerator();
  17. }
  18. //TODO 这里只是为了兼容下,并没多大重要,方法标记过时了.
  19. IdWorker.setIdentifierGenerator(identifierGenerator);
  20. if (globalConfig.isEnableSqlRunner()) {
  21. new SqlRunnerInjector().inject(configuration);
  22. }
  23. SqlSessionFactory sqlSessionFactory = super.build(configuration);
  24. // 缓存 sqlSessionFactory
  25. globalConfig.setSqlSessionFactory(sqlSessionFactory);
  26. return sqlSessionFactory;
  27. }

默认情况下,调试执行代码:

  1. identifierGenerator = new DefaultIdentifierGenerator();

即SqlSessionFactory默认使用雪花算法,globalConfig全局配置默认为雪花算法