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.table;
017
018import com.mybatisflex.annotation.Id;
019import com.mybatisflex.annotation.KeyType;
020import com.mybatisflex.core.FlexGlobalConfig;
021import com.mybatisflex.core.util.StringUtil;
022
023public class IdInfo extends ColumnInfo {
024
025    /**
026     * id 生成策略
027     */
028    private KeyType keyType;
029
030    /**
031     * 1、若 keyType 类型是 sequence, value 则代表的是
032     * sequence 序列的 sql 内容
033     * 例如:select SEQ_USER_ID.nextval as id from dual
034     * <p>
035     * 2、若 keyType 是 Generator,value 则代表的是使用的那个 keyGenerator 的名称
036     */
037    private String value;
038
039
040    /**
041     * sequence 序列内容执行顺序
042     *
043     * @see org.apache.ibatis.executor.keygen.SelectKeyGenerator
044     */
045    private Boolean before;
046
047
048    public IdInfo(Id id) {
049        this.keyType = id.keyType();
050        this.value = id.value();
051        this.before = id.before();
052
053        initDefaultKeyType();
054    }
055
056    /**
057     * 用户未配置 keyType 是,配置默认的 key Type
058     */
059    private void initDefaultKeyType() {
060        if (this.keyType == null || this.keyType == KeyType.None) {
061            FlexGlobalConfig.KeyConfig defaultKeyConfig = FlexGlobalConfig.getDefaultConfig().getKeyConfig();
062            if (defaultKeyConfig != null) {
063                if (defaultKeyConfig.getKeyType() != null) {
064                    this.keyType = defaultKeyConfig.getKeyType();
065                    this.before = defaultKeyConfig.isBefore();
066                }
067                if (StringUtil.isBlank(this.value) && StringUtil.isNotBlank(defaultKeyConfig.getValue())) {
068                    this.value = defaultKeyConfig.getValue();
069                }
070            }
071        }
072    }
073
074
075    public KeyType getKeyType() {
076        return keyType;
077    }
078
079    public void setKeyType(KeyType keyType) {
080        this.keyType = keyType;
081    }
082
083    public String getValue() {
084        return value;
085    }
086
087    public void setValue(String value) {
088        this.value = value;
089    }
090
091    public Boolean getBefore() {
092        return before;
093    }
094
095    public void setBefore(Boolean before) {
096        this.before = before;
097    }
098
099}