001/*
002 *  Copyright (c) 2022-2023, 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.UUIDKeyGenerator;
023import com.mybatisflex.core.util.StringUtil;
024
025import java.util.HashMap;
026import java.util.Map;
027
028public class KeyGeneratorFactory {
029
030    private KeyGeneratorFactory() {
031    }
032
033    private static final Map<String, IKeyGenerator> KEY_GENERATOR_MAP = new HashMap<>();
034
035    static {
036        /** 内置了 uuid 的生成器,因此主键配置的时候可以直接配置为 @Id(keyType = KeyType.Generator, value = "uuid")
037         * {@link com.mybatisflex.annotation.Id}
038         */
039        register(KeyGenerators.uuid, new UUIDKeyGenerator());
040        register(KeyGenerators.flexId, new FlexIDKeyGenerator());
041        register(KeyGenerators.snowFlakeId, new SnowFlakeIDKeyGenerator());
042    }
043
044
045    /**
046     * 获取 主键生成器
047     *
048     * @param name
049     * @return 主键生成器
050     */
051    public static IKeyGenerator getKeyGenerator(String name) {
052        if (StringUtil.isBlank(name)){
053            throw FlexExceptions.wrap(LocalizedFormats.KEY_GENERATOR_BLANK);
054        }
055        return KEY_GENERATOR_MAP.get(name.trim());
056    }
057
058
059    /**
060     * 注册一个主键生成器
061     *
062     * @param key
063     * @param keyGenerator
064     */
065    public static void register(String key, IKeyGenerator keyGenerator) {
066        KEY_GENERATOR_MAP.put(key.trim(), keyGenerator);
067    }
068
069}