All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.swiftboot.data.model.id.EntityIdGenerator Maven / Gradle / Ivy

There is a newer version: 2.4.8
Show newest version
package org.swiftboot.data.model.id;

import org.apache.commons.lang3.StringUtils;
import org.swiftboot.data.model.entity.IdPersistable;
import org.swiftboot.util.IdUtils;
import org.swiftboot.util.WordUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 实体类 ID 生成器
 *
 * @author swiftech
 **/
public class EntityIdGenerator implements IdGenerator {

    public static final int MIN_CODE_LEN = 2;
    public static final int MAX_CODE_LEN = 6;

    // 类和业务代码映射缓存
    private final Map, String> classCodeMapping = new HashMap<>();

    @Override
    public String generate(IdPersistable object) {
        // 自动根据业务对象名称生成业务对象代码,
        Class entityClass = object.getClass();
        String code = null;
        if (classCodeMapping.containsKey(entityClass)) {
            code = classCodeMapping.get(entityClass);
        }
        else {
            String simpleEntityName = entityClass.getSimpleName();
            String bizName = StringUtils.substringBefore(simpleEntityName, "Entity");
            if (bizName.length() < MIN_CODE_LEN) {
                code = StringUtils.rightPad(bizName.toLowerCase(), MIN_CODE_LEN, "entity");
            }
            else {
                code = camelToShort(bizName, MAX_CODE_LEN);
            }
            classCodeMapping.put(entityClass, code);
        }
        return IdUtils.makeID(code);
    }

    private String camelToShort(String camel, int len) {
        String[] words = StringUtils.splitByCharacterTypeCamelCase(camel);
        return WordUtils.joinWords(words, len);
    }


}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy