怎么用java实现驼峰命名法与数据库命名法的相互转换
发布网友
发布时间:2022-04-07 05:47
我来回答
共4个回答
热心网友
时间:2022-04-07 07:17
手敲的,给个辛苦分吧。。。
package test;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
//testing for data base column-key to java field
String[] dbKeys = {"id", "user_age", "user_addr_"};
Test t = new Test();
t.convertToJava(dbKeys);
System.out.println("-----------------------------------");
//testing for Java field to data base column-key
String javaFieldNames[] = {"id","userAge","userHomeAddr"};
t.getDBKey(javaFieldNames);
}
/*
* Java field to data base column-key
*/
private void getDBKey(String... javaFieldNames){
if(javaFieldNames != null && javaFieldNames.length > 0){
for(String name : javaFieldNames){
StringBuffer buffer = new StringBuffer();
char[] array = name.toCharArray();
List<Integer> insertIndexes = new ArrayList<>();
for(int i=0;i<array.length;i++){
Character c = array[i];
if(i != 0 && Character.isUpperCase(c)){
insertIndexes.add(i);
}
}
if(insertIndexes.size() > 0){
int flag = 0;
for(int j=0;j<insertIndexes.size();j++){
String word = toLowercase4FirstLetter(name.substring(flag, insertIndexes.get(j)));
buffer.append(word).append("_");
flag = insertIndexes.get(j);
}
String last = toLowercase4FirstLetter(name.substring(flag));
buffer.append(last);
System.out.println(buffer.toString());
} else {
System.out.println(name);
}
}
}
}
private String toLowercase4FirstLetter(String word){
if(word != null && word.length() > 0){
String firstLetter = word.substring(0,1);
String others = word.substring(1);
return firstLetter.toLowerCase() + others;
}else{
return "";
}
}
/*
* data base column-key to java field
*/
public void convertToJava(String... dbKeys) {
if(dbKeys != null && dbKeys.length > 0){
for(String key : dbKeys){
String[] words = key.split("_");
String result = toUppercase4FirstLetter(words);
System.out.println(result);
}
}
}
private String toUppercase4FirstLetter(String... words){
StringBuffer buffer = new StringBuffer();
if(words != null && words.length > 0){
for(int i=0;i<words.length;i++){
String word = words[i];
String firstLetter = word.substring(0, 1);
String others = word.substring(1);
String upperLetter = null;
if(i != 0){
upperLetter = firstLetter.toUpperCase();
} else {
upperLetter = firstLetter;
}
buffer.append(upperLetter).append(others);
}
return buffer.toString();
}
return "";
}
}
热心网友
时间:2022-04-07 08:35
驼峰命名就是除首单词外后面单词第一个字符大写,根据数据库命名法规则,获取到一个名字时先判断是表名还是什么,然后根据对应的规则剪切拼接字符就可以了。
热心网友
时间:2022-04-07 10:09
如果用mybatis可以直接转换的。
热心网友
时间:2022-04-07 12:01
请教一下,数据库命名法是怎么命名的