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

matrix.boot.jdbc.utils.EntityParseUtil Maven / Gradle / Ivy

The newest version!
package matrix.boot.jdbc.utils;

import matrix.boot.common.exception.ServiceException;
import matrix.boot.common.utils.BIOStreamUtil;
import matrix.boot.common.utils.StringUtil;
import matrix.boot.jdbc.dto.EntityFieldDto;
import matrix.boot.jdbc.dto.EntityInfoDto;

import java.io.FileInputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Locale;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 实体解析工具
 *
 * @author wangcheng
 * 2022/4/2
 **/
public class EntityParseUtil {

    /**
     * 实体 包名
     */
    private static final String ENTITY_NAME = "entity";

    /**
     * 解析实体信息
     *
     * @param clazz 实体类
     * @return 实体信息
     */
    public static EntityInfoDto parse(Class clazz) {
        String className = clazz.getName();
        if (!className.endsWith("Entity")) {
            throw new ServiceException(className + " must end with 'Entity'");
        }
        EntityInfoDto result = new EntityInfoDto();
        //表名
        String tableName = className.substring(className.lastIndexOf(".") + 1).replace("Entity", "");
        result.setTableName(tableName);
        //定义表名(首字母小写)
        result.setDefineTableName(tableName.substring(0, 1).toLowerCase() + tableName.substring(1));
        //包名
        String packageName = className.replace("." + ENTITY_NAME + "." + tableName + "Entity", "");
        result.setPackageName(packageName);
        //项目路径
        String workspacePath = Objects.requireNonNull(clazz.getResource("")).getPath().split("/target/classes")[0];
        result.setWorkspacePath(workspacePath);
        //原始java路径
        String originJavaPath = workspacePath + "/src/main/java/";
        result.setOriginJavaPath(originJavaPath);
        //java路径
        String javaPath = originJavaPath + String.join("/", packageName.split("\\."));
        result.setJavaPath(javaPath);
        //resources路径
        String resourcesPath = workspacePath + "/src/main/resources/";
        result.setResourcesPath(resourcesPath);
        //解析字段信息
        parseFields(result, clazz);
        //解析实体代码
        parseEntityCode(result, clazz);
        return result;
    }

    /**
     * 解析字段信息
     *
     * @param result 实体信息
     * @param clazz  实体类
     */
    private static void parseFields(EntityInfoDto result, Class clazz) {
        Class superClass = clazz.getSuperclass();
        if (superClass.getName().endsWith("Entity")) {
            parseFields(result, superClass);
        }
        Field[] fields = clazz.getDeclaredFields();
        if (fields.length <= 0) {
            return;
        }
        for (Field field : fields) {
            //分析主键
            if (isPrimary(field) && StringUtil.isEmpty(result.getDefinePrimaryFieldName())) {
                result.setDefinePrimaryFieldName(field.getName());
                result.setPrimaryFieldName(field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1));
                result.setPrimaryFieldType(getFieldType(field));
            }
            if (result.getFields() == null) {
                result.setFields(new ArrayList<>());
            }
            result.getFields().add(new EntityFieldDto()
                    .setField(field.getName())
                    .setFieldType(getFieldType(field))
                    .setImportFieldType(field.getType().getName()));
            //放入特殊导入类型
            if (!field.getType().getName().startsWith("java.lang")) {
                result.getSpecialImportFieldTypeClasses().add(field.getType().getName());
            }
        }
    }

    /**
     * 解析实体代码
     *
     * @param result 实体信息
     * @param clazz  实体类
     */
    private static void parseEntityCode(EntityInfoDto result, Class clazz) {
        Class superClass = clazz.getSuperclass();
        if (superClass.getName().endsWith("Entity")) {
            parseEntityCode(result, superClass);
        }
        //实体路径
        String entityPath = result.getOriginJavaPath() + "/"
                + String.join("/", clazz.getName().split("\\.")) + ".java";
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(entityPath);
            String entityCode = BIOStreamUtil.streamToString(fis);
            Pattern pattern = Pattern.compile("\\{[\\s\\S]+}");
            Matcher matcher = pattern.matcher(entityCode);
            while (matcher.find()) {
                String content = matcher.group();
                content = content.substring(1, content.length() - 1);
                String[] rows = content.split("\n");
                for (int i = 1; i < rows.length; i++) {
                    String row = rows[i];
                    if (row.contains("@TableId") || row.contains("@Id")
                            || row.contains("@TableField") || row.contains("@Column")
                            || row.contains("@TableLogic") || row.contains("@JsonSerialize")
                            || row.contains("@JsonDeserialize")) {
                        continue;
                    }
                    result.setEntityCode(result.getEntityCode() + row);
                }
            }
        } catch (Exception e) {
            throw new ServiceException(e);
        } finally {
            BIOStreamUtil.closeStream(fis);
        }
    }

    /**
     * 是否主键
     *
     * @param field 字段
     * @return 是否
     */
    private static boolean isPrimary(Field field) {
        Annotation[] annotations = field.getDeclaredAnnotations();
        for (Annotation annotation : annotations) {
            if (annotation.toString().contains("com.baomidou.mybatisplus.annotation.TableId")
                    || annotation.toString().contains("javax.persistence.Id"))
                return true;
        }
        return false;
    }

    /**
     * 获取字段类型
     *
     * @param field 字段
     * @return 字段类型
     */
    private static String getFieldType(Field field) {
        String typeStr = field.getType().toString();
        return typeStr.substring(typeStr.lastIndexOf(".") + 1);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy