テーブルをjavabeanに転送(mysqlベース)
16441 ワード
仕事中、javabeanを書く仕事に遭遇します.毎回気持ち悪く書いて、表とフィールドは下線です.例えば、created_date;javabeanはアルパカで、例えばcreatedDateです.では、次のようなツールクラスが必要です.
下線回転アルパカのツールクラス
そうですね.
JAva学習と交流群:22160972
/**
* ,
* @author lqx
*
*/
public class GenEntityMysql {
private String packageOutPath = "com.funsmart.model";//
private String namespacePrefix= "com.funsmart.dao"; // mapper
private String mapperOutPath= "com.funsmart.mapper"; // mapper
private String authorName = "lqx";//
private String tablename = "";//
private String className = "";//
private String[] colnames; //
private String[] colTypes; //
private int[] colSizes; //
private boolean f_util = false; // java.util.*
private boolean f_sql = false; // java.sql.*
private boolean f_jpa = false; // JPA
//
private static final String URL ="jdbc:mysql://127.0.0.1:3306/demo";
private static final String NAME = "root";
private static final String PASS = "root";
private static final String DRIVER ="com.mysql.jdbc.Driver";
/*
*
*/
public GenEntityMysql(){
}
/**
* JavaBean
*/
public void genAllTablToBean(){
List<String> list=getTableName();
for(int p=0;p<list.size();p++){
tablename=list.get(p);
className = getClassName(tablename);
//
Connection con;
//
String sql = "select * from " + tablename;
PreparedStatement pStemt = null;
try {
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
con = DriverManager.getConnection(URL,NAME,PASS);
pStemt = con.prepareStatement(sql);
ResultSetMetaData rsmd = pStemt.getMetaData();
int size = rsmd.getColumnCount(); //
colnames = new String[size];
colTypes = new String[size];
colSizes = new int[size];
for (int i = 0; i < size; i++) {
colnames[i] = rsmd.getColumnName(i + 1);
colTypes[i] = rsmd.getColumnTypeName(i + 1);
if(colTypes[i].equalsIgnoreCase("datetime")){
f_util = true;
}
if(colTypes[i].equalsIgnoreCase("image") || colTypes[i].equalsIgnoreCase("text")){
f_sql = true;
}
colSizes[i] = rsmd.getColumnDisplaySize(i + 1);
}
String content = parse(colnames,colTypes,colSizes);
try {
File directory = new File("");
String outputPath = directory.getAbsolutePath()+ "/src/main/java/"+this.packageOutPath.replace(".", "/")+"/"+initcap(className) + ".java";
FileWriter fw = new FileWriter(outputPath);
PrintWriter pw = new PrintWriter(fw);
pw.println(content);
pw.flush();
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (SQLException e) {
e.printStackTrace();
} finally{
// try {
// con.close();
// } catch (SQLException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
}
}
System.out.println(" !");
}
/**
*
* JavaBean
*/
public void genTablToBean(String tableName){
// List<String> list=getTableName();
// for(int p=0;p<list.size();p++){
tablename=tableName;
className = getClassName(tablename);
//
Connection con;
//
String sql = "select * from " + tablename;
PreparedStatement pStemt = null;
try {
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
con = DriverManager.getConnection(URL,NAME,PASS);
pStemt = con.prepareStatement(sql);
ResultSetMetaData rsmd = pStemt.getMetaData();
int size = rsmd.getColumnCount(); //
colnames = new String[size];
colTypes = new String[size];
colSizes = new int[size];
for (int i = 0; i < size; i++) {
colnames[i] = rsmd.getColumnName(i + 1);
colTypes[i] = rsmd.getColumnTypeName(i + 1);
if(colTypes[i].equalsIgnoreCase("datetime")){
f_util = true;
}
if(colTypes[i].equalsIgnoreCase("image") || colTypes[i].equalsIgnoreCase("text")){
f_sql = true;
}
colSizes[i] = rsmd.getColumnDisplaySize(i + 1);
}
String content = parse(colnames,colTypes,colSizes);
try {
File directory = new File("");
String outputPath = directory.getAbsolutePath()+ "/src/main/java/"+this.packageOutPath.replace(".", "/")+"/"+initcap(className) + ".java";
FileWriter fw = new FileWriter(outputPath);
PrintWriter pw = new PrintWriter(fw);
pw.println(content);
pw.flush();
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (SQLException e) {
e.printStackTrace();
} finally{
// try {
// con.close();
// } catch (SQLException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
}
// }
System.out.println(" !");
}
/**
* Java
* @param con
*/
private List<String> getTableName() {
List<String> list=new ArrayList<String>();
try {
DatabaseMetaData meta = DriverManager.getConnection(URL,NAME,PASS).getMetaData();
ResultSet rs = meta.getTables(null, null, null,new String[]{"TABLE"});
while (rs.next()) {
String tableName = rs.getString(3);
//
if(StringUtils.isNotBlank(tableName)){
list.add(tableName);
}
}
}catch(Exception e){
e.printStackTrace();
}
return list;
}
/**
*
* @param tableName
* @return
*/
private String getClassName(String tableName){
// t_
tableName = StringUtils.removeStart(tableName, "t_");
tableName = FieldUtils.camelName(tableName);
return tableName;
}
/**
* :
* @param colnames
* @param colTypes
* @param colSizes
* @return
*/
private String parse(String[] colnames, String[] colTypes, int[] colSizes) {
StringBuffer sb = new StringBuffer();
sb.append("package " + this.packageOutPath + ";\r
");
sb.append("\r
");
//
if(f_util){
sb.append("import java.util.Date;\r
");
}
if(f_sql){
sb.append("import java.sql.*;\r
");
}
//jpa
if(f_jpa){
sb.append("import javax.persistence.Entity;\r
");
sb.append("import javax.persistence.GeneratedValue;\r
");
sb.append("import javax.persistence.GenerationType;\r
");
sb.append("import javax.persistence.Id;\r
\r
");
}
//
sb.append("/**\r
");
sb.append(" * "+className+" \r
");
sb.append(" * "+new Date()+"\r
");
sb.append(" * @"+this.authorName+"\r
");
sb.append(" */ \r
");
if(f_jpa){
sb.append("@Entity\r
");
}
//
sb.append("public class " + initcap(className) + "{\r
\r
");
processAllAttrs(sb);//
processAllMethod(sb);//get set
sb.append("}\r
");
//System.out.println(sb.toString());
return sb.toString();
}
/**
* :
* @param sb
*/
private void processAllAttrs(StringBuffer sb) {
for (int i = 0; i < colnames.length; i++) {
String fieldStr = colnames[i];
if(fieldStr.indexOf("_") != -1){
fieldStr = FieldUtils.camelName(fieldStr);
}
sb.append("\tprivate " + sqlType2JavaType(colTypes[i]) + " " + fieldStr + ";\r
");
}
sb.append("\r
");
}
/**
* :
* @param sb
*/
private void processAllMethod(StringBuffer sb) {
for (int i = 0; i < colnames.length; i++) {
String fieldStr = colnames[i];
if(fieldStr.indexOf("_") != -1){
fieldStr = FieldUtils.camelName(fieldStr);
}
if(f_jpa){
if(i==0){
sb.append("\t@Id\r
");
sb.append("\t@GeneratedValue(strategy = GenerationType.AUTO)\r
");
sb.append("\tpublic " + sqlType2JavaType(colTypes[i]) + " get" + initcap(fieldStr) + "(){\r
");
}else{
sb.append("\tpublic " + sqlType2JavaType(colTypes[i]) + " get" + initcap(fieldStr) + "(){\r
");
}
}else{
sb.append("\tpublic " + sqlType2JavaType(colTypes[i]) + " get" + initcap(fieldStr) + "(){\r
");
}
sb.append("\t\treturn " + fieldStr + ";\r
");
sb.append("\t}\r
\r
");
sb.append("\tpublic void set" + initcap(fieldStr) + "(" + sqlType2JavaType(colTypes[i]) + " " + fieldStr + "){\r
");
sb.append("\t\tthis." + fieldStr + "=" + fieldStr + ";\r
");
sb.append("\t}\r
\r
");
}
}
/**
* :
* @param str
* @return
*/
private String initcap(String str) {
char[] ch = str.toCharArray();
if(ch[0] >= 'a' && ch[0] <= 'z'){
ch[0] = (char)(ch[0] - 32);
}
return new String(ch);
}
/**
* :
* @param sqlType
* @return
*/
private String sqlType2JavaType(String sqlType) {
if(sqlType.equalsIgnoreCase("bit")){
return "boolean";
}else if(sqlType.equalsIgnoreCase("tinyint")){
return "int";
}else if(sqlType.equalsIgnoreCase("smallint")){
return "int";
}else if(sqlType.equalsIgnoreCase("int")||sqlType.equalsIgnoreCase("INT UNSIGNED")){
//INT UNSIGNED
return "int";
}else if(sqlType.equalsIgnoreCase("bigint")){
return "long";
}else if(sqlType.equalsIgnoreCase("float")){
return "float";
}else if(sqlType.equalsIgnoreCase("decimal") || sqlType.equalsIgnoreCase("numeric")
|| sqlType.equalsIgnoreCase("real") || sqlType.equalsIgnoreCase("money")
|| sqlType.equalsIgnoreCase("smallmoney")){
return "double";
}else if(sqlType.equalsIgnoreCase("varchar") || sqlType.equalsIgnoreCase("char")
|| sqlType.equalsIgnoreCase("nvarchar") || sqlType.equalsIgnoreCase("nchar")
|| sqlType.equalsIgnoreCase("text")){
return "String";
}else if(sqlType.equalsIgnoreCase("datetime")){
return "Date";
}else if(sqlType.equalsIgnoreCase("image")){
return "Blod";
}
return null;
}
/**
*
* TODO
* @param args
*/
public static void main(String[] args) {
new GenEntityMysql().genTablToBean("t_city");
}
}
下線回転アルパカのツールクラス
/**
*
*
*
* User: linqx
* Time: 2015-07-22 22:58
*/
public class FieldUtils {
/**
* 。 , 。</br>
* :HelloWorld->HELLO_WORLD
* @param name
* @return
*/
public static String underscoreName(String name) {
StringBuilder result = new StringBuilder();
if (name != null && name.length() > 0) {
//
result.append(name.substring(0, 1).toUpperCase());
//
for (int i = 1; i < name.length(); i++) {
String s = name.substring(i, i + 1);
//
if (s.equals(s.toUpperCase()) && !Character.isDigit(s.charAt(0))) {
result.append("_");
}
//
result.append(s.toUpperCase());
}
}
return result.toString();
}
/**
* 。 , 。</br>
* :HELLO_WORLD->HelloWorld
* @param name
* @return
*/
public static String camelName(String name) {
StringBuilder result = new StringBuilder();
//
if (name == null || name.isEmpty()) {
//
return "";
} else if (!name.contains("_")) {
// ,
return name.substring(0, 1).toLowerCase() + name.substring(1);
}
//
String camels[] = name.split("_");
for (String camel : camels) {
// 、
if (camel.isEmpty()) {
continue;
}
//
if (result.length() == 0) {
// ,
result.append(camel.toLowerCase());
} else {
// ,
result.append(camel.substring(0, 1).toUpperCase());
result.append(camel.substring(1).toLowerCase());
}
}
return result.toString();
}
}
そうですね.
JAva学習と交流群:22160972