package org.yeshi.utils.generater.mybatis;
|
|
import org.springframework.data.annotation.Transient;
|
|
import java.lang.annotation.Annotation;
|
import java.lang.reflect.Field;
|
|
public class ColumnParseUtil {
|
|
/**
|
* 将属性转为数据库字段
|
*
|
* @param fieldName
|
* @return
|
*/
|
private static String convertFieldToColumn(String fieldName) {
|
String column = "";
|
for (int i = 0; i < fieldName.length(); i++) {
|
//大写字母
|
if (fieldName.charAt(i) >= 65 && fieldName.charAt(i) <= 90) {
|
//前面一个为非大写
|
if (i > 0 && (fieldName.charAt(i - 1) < 65 || fieldName.charAt(i - 1) > 90)) {
|
column += "_" + fieldName.charAt(i);
|
} else {
|
column += fieldName.charAt(i);
|
}
|
} else {
|
column += fieldName.charAt(i);
|
}
|
}
|
return column.toLowerCase();
|
}
|
|
public static void parseColumn(Class<?> clz, String path) {
|
Field[] fields = clz.getDeclaredFields();
|
for (Field fd : fields) {
|
|
//private/public 非final,static属性才会参与解析
|
if (fd.getModifiers() != 1 && fd.getModifiers() != 2) {
|
continue;
|
}
|
|
|
String columName = convertFieldToColumn(fd.getName());
|
Annotation[] as = fd.getAnnotations();
|
for (Annotation a : as) {
|
//不参与解析
|
if (a instanceof Column) {
|
Column c = (Column) a;
|
columName = c.name();
|
|
}
|
}
|
|
for (Annotation a : as) {
|
//不参与解析
|
if (a instanceof Transient || a instanceof java.beans.Transient) {
|
columName = null;
|
break;
|
}
|
}
|
|
if (columName != null) {
|
ColumnUtil.addColumnToMapper(path, columName, fd.getName(), getJDBCType(fd.getType().getName()));
|
}
|
|
}
|
}
|
|
public static String getJDBCType(String type) {
|
if (type.endsWith("java.lang.Long")) {
|
return "BIGINT";
|
} else if (type.endsWith("java.lang.Integer")) {
|
return "INTEGER";
|
} else if (type.endsWith("java.lang.String")) {
|
return "VARCHAR";
|
} else if (type.endsWith("java.lang.Boolean")) {
|
return "BOOLEAN";
|
} else if (type.endsWith("java.math.BigDecimal")) {
|
return "DECIMAL";
|
} else if (type.endsWith("java.util.Date")) {
|
return "TIMESTAMP";
|
} else if (type.endsWith("java.lang.Double")) {
|
return "DOUBLE";
|
} else {
|
return "VARCHAR";
|
}
|
}
|
|
|
public static String getMysqlType(String type) {
|
if (type.endsWith("java.lang.Long")) {
|
return "bigint";
|
} else if (type.endsWith("java.lang.Integer")) {
|
return "int";
|
} else if (type.endsWith("java.lang.String")) {
|
return "varchar";
|
} else if (type.endsWith("java.lang.Boolean")) {
|
return "tinyint";
|
} else if (type.endsWith("java.math.BigDecimal")) {
|
return "decimal";
|
} else if (type.endsWith("java.util.Date")) {
|
return "datetime";
|
} else if (type.endsWith("java.lang.Double")) {
|
return "double";
|
} else {
|
return "varchar";
|
}
|
}
|
|
}
|