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