001/* 002 * Copyright (c) 2022-2025, Mybatis-Flex (fuhai999@gmail.com). 003 * <p> 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * <p> 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * <p> 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package com.mybatisflex.core.keygen; 017 018import com.mybatisflex.core.exception.FlexExceptions; 019import com.mybatisflex.core.exception.locale.LocalizedFormats; 020import com.mybatisflex.core.keygen.impl.FlexIDKeyGenerator; 021import com.mybatisflex.core.keygen.impl.SnowFlakeIDKeyGenerator; 022import com.mybatisflex.core.keygen.impl.ULIDKeyGenerator; 023import com.mybatisflex.core.keygen.impl.UUIDKeyGenerator; 024import com.mybatisflex.core.util.StringUtil; 025 026import java.util.HashMap; 027import java.util.Map; 028 029public class KeyGeneratorFactory { 030 031 private KeyGeneratorFactory() { 032 } 033 034 private static final Map<String, IKeyGenerator> KEY_GENERATOR_MAP = new HashMap<>(); 035 036 static { 037 /** 内置了 uuid 的生成器,因此主键配置的时候可以直接配置为 @Id(keyType = KeyType.Generator, value = "uuid") 038 * {@link com.mybatisflex.annotation.Id} 039 */ 040 register(KeyGenerators.uuid, new UUIDKeyGenerator()); 041 register(KeyGenerators.flexId, new FlexIDKeyGenerator()); 042 register(KeyGenerators.snowFlakeId, new SnowFlakeIDKeyGenerator()); 043 register(KeyGenerators.ulid, new ULIDKeyGenerator()); 044 045 } 046 047 048 /** 049 * 获取 主键生成器 050 * 051 * @param name 052 * @return 主键生成器 053 */ 054 public static IKeyGenerator getKeyGenerator(String name) { 055 if (StringUtil.noText(name)) { 056 throw FlexExceptions.wrap(LocalizedFormats.KEY_GENERATOR_BLANK); 057 } 058 return KEY_GENERATOR_MAP.get(name.trim()); 059 } 060 061 062 /** 063 * 注册一个主键生成器 064 * 065 * @param key 066 * @param keyGenerator 067 */ 068 public static void register(String key, IKeyGenerator keyGenerator) { 069 KEY_GENERATOR_MAP.put(key.trim(), keyGenerator); 070 } 071 072}