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