引类
* @author Lufeng
*
*/
public class GenDB {
private String sourceDir; // 配置源文件夹
public GenDB(String source) {
this.sourceDir = source;
}
/**
* 获取不同类型默认长度
* @param clazz
* @param obj
* @param type
* @return
* @throws Exception
*/
public int getDefaultLength(String type) throws Exception {
int length = 0;
if(type == null) {
throw new RuntimeException("不能识别的类型:" + type);
}
// 根据不同类型返回不同默认长度
if("int".equals(type)) {
length = TYPE_DEFUALT_INT;;
} else if("long".equals(type)) {
length = TYPE_DEFUALT_LONG;
} else if("String".equals(type)) {
length = TYPE_DEFUALT_STRING;
}
return length;
}
public String getSqlType(String type) {
String result = "";
if("int".equals(type)) {
result = "integer";
} else if("long".equals(type)) {
result = "bigint";
} else if("String".equals(type)) {
result = "varchar";
}
return result;
}
/**
* 获取配置类中的所有字段名
* @param clazz
* @return
*/
public List getColumns(Class< > clazz) {
List result = new ArrayList();
// 获得所有枚举字段成员(id, account, name, profession...),并遍历获取字段名
Object[] enums = clazz.getEnumConstants();
result.add("id"); // id是默认添加的
for (Object e : enums) {
result.add(e.toString());
}
return result;
}
/**
* 获取所有约束信息
* @param clazz
* @param obj
* @return
* @throws Exception
*/
public Map getFieldInfo(Class< > clazz, Object obj) throws Exception {
Map result = new HashMap();
// 获取所有约束信息
String name = obj.toString();
String typeName = ((Class< >) GenUtils.getFieldValue(clazz, obj, TYPE)).getSimpleName();
String type = getSqlType(typeName);
int length = (Integer) GenUtils.getFieldValue(clazz, obj, LENGTH);
boolean index = (Boolean) GenUtils.getFieldValue(clazz, obj, INDEX);
String nullable = (Boolean) GenUtils.getFieldValue(clazz, obj, NULLABLE) == true "NULL" : "NOT NULL";
//默认值
Object def = GenUtils.getFieldValue(clazz, obj, DEFAULTS);
String defaults = def == null "" : " DEFAULT '" + def.toString() + "'";
// 如果长度为0,即没设长度,则提取默认值
if(length == 0) {
length = getDefaultLength(typeName);
}
result.put("name", name);
result.put(TYPE, type);
result.put(LENGTH, length);
result.put(INDEX, index);
result.put(NULLABLE, nullable);
result.put(DEFAULTS, defaults);
return result;
}
/**
* 获取表中所有字段信息
* @param clazz
* @return
* @throws Exception
*/
public List