駝峯命名反轉換
private static String toUnderlineName(String s) {
if (s == null) {
return null;
}
StringBuilder sb = new StringBuilder();
boolean upperCase = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
boolean nextUpperCase = true;
if (i < (s.length() - 1)) {
nextUpperCase = Character.isUpperCase(s.charAt(i + 1));
}
if ((i >= 0) && Character.isUpperCase(c)) {
if (!upperCase || !nextUpperCase) {
if (i > 0) sb.append(SEPARATOR);
}
upperCase = true;
} else {
upperCase = false;
}
sb.append(Character.toUpperCase(c));
}
return sb.toString();
}
Object轉InsertSql
public static String objectByInsertSQL(Object object){
String tableName = toUnderlineName(object.getClass().getSimpleName());
String insertSql = "INSERT INTO "+tableName;
String attribute = "";
String attributeValue = "";
Field[] fields = object.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
String name = toUnderlineName(field.getName());
String type = field.getGenericType().toString();
Object value = null;
try {
value = field.get(object);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
attribute += name+",";
if (value != null && type.equals("class java.lang.String")){
attributeValue += "'"+value+"',";
}else {
attributeValue += value+",";
}
}
return insertSql + "("+attribute.substring(0,attribute.length()-1)+") VALUES ("+attributeValue.substring(0,attributeValue.length()-1)+")";
}
Object轉UpdateSql
public static String objectByUpdateSQL(Object object, List<String> keys){
String tableName = toUnderlineName(object.getClass().getSimpleName());
String updateSql = "UPDATE "+tableName+ " SET ";
String attribute = "";
String attributeValue = "";
String condition = "";
Field[] fields = object.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
String name = toUnderlineName(field.getName());
Object value = null;
String type = field.getGenericType().toString();
try {
value = field.get(object);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
if (value != null && type.equals("class java.lang.String")) {
value = "'"+value+"'";
}
boolean isCondition = true;
for (String key : keys){
if (key.equals(name)){
condition += name + "=" + value+" AND ";
isCondition = false;
}
}
if (isCondition){
updateSql += name + "=" + value + ",";
}
}
return updateSql.substring(0,updateSql.length()-1) + " WHERE " +condition.substring(0,condition.length()-4);
}