1.配置JavaBean与数据库表字段映射关系
/**
* 字段转换方式
*/
public enum Style {
normal, //原值
camelhump, //驼峰转下划线
uppercase, //转换为大写
lowercase, //转换为小写
camelhumpAndUppercase, //驼峰转下划线大写形式
camelhumpAndLowercase, //驼峰转下划线小写形式
}
根据实体类名称转换表名称
/**
* 根据指定的样式进行转换
*
* @param str
* @param style
* @return
*/
public static String convertByStyle(String str, Style style) {
switch (style) {
case camelhump:
return camelhumpToUnderline(str);
case uppercase:
return str.toUpperCase();
case lowercase:
return str.toLowerCase();
case camelhumpAndLowercase:
return camelhumpToUnderline(str).toLowerCase();
case camelhumpAndUppercase:
return camelhumpToUnderline(str).toUpperCase();
case normal:
default:
return str;
}
具体的转换方式
/**
* 将驼峰风格替换为下划线风格
*/
public static String camelhumpToUnderline(String str) {
final int size;
final char[] chars;
final StringBuilder sb = new StringBuilder(
(size = (chars = str.toCharArray()).length) * 3 / 2 + 1);
char c;
for (int i = 0; i < size; i++) {
c = chars[i];
if (isUppercaseAlpha(c)) {
sb.append('_').append(toLowerAscii(c));
} else {
sb.append(c);
}
}
return sb.charAt(0) == '_' ? sb.substring(1) : sb.toString();
}
2.通过反射JavaBean拿到所有的field
/**
* 获取全部的Field,仅仅通过Field获取
*
* @param entityClass
* @param fieldList
* @param level
* @return
*/
private List<EntityField> _getFields(Class<?> entityClass, List<EntityField> fieldList, Integer level) {
if (fieldList == null) {
fieldList = new ArrayList<EntityField>();
}
if (level == null) {
level = 0;
}
if (entityClass.equals(Object.class)) {
return fieldList;
}
Field[] fields = entityClass.getDeclaredFields();
int index = 0;
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
//排除静态字段,解决bug#2
if (!Modifier.isStatic(field.getModifiers()) && !Modifier.isTransient(field.getModifiers())) {
if (level.intValue() != 0) {
//将父类的字段放在前面
fieldList.add(index, new EntityField(field, null));
index++;
} else {
fieldList.add(new EntityField(field, null));
}
}
}
Class<?> superClass = entityClass.getSuperclass();
if (superClass != null
&& !superClass.equals(Object.class)
&& (superClass.isAnnotationPresent(Entity.class)
|| (!Map.class.isAssignableFrom(superClass)
&& !Collection.class.isAssignableFrom(superClass)))) {
return _getFields(entityClass.getSuperclass(), fieldList, ++level);
}
return fieldList;
}