Dan satu lagi SQL2O belum ada tool untuk generate tabel to pojo secara auto. dan oleh sebab itu... kemaren ada yg nanya juga, kali ini saya sedikit share bagamana cara gila generate tabel db to pojo.
public class Nera extends SingleFrameApplication {
JLabel label;
@Override
protected void startup() {
ColumnDAO dao = new ColumnDAO();
List<ColumnModel> list = dao.getColumnInfo("try2.student");
for (ColumnModel columnModel : list) {
System.out.println("private "+getVeriabel(columnModel.getType())+" "+getVeriabelName(columnModel.getField()) +";");
}
System.out.println("Map<String, String> map = new HashMap();");
}
String getVeriabel(String type){
String[] typeOne = type.split("\\(");
String typeJava = Preference.map.get(typeOne[0]);
if(typeJava==null){
typeJava = Preference.map.get(typeOne[0].toUpperCase());
}
if(typeJava!=null && typeJava.equals("enum")){//need additional
String[] enumtypes = typeJava.split("\\)");
String[] enums = enumtypes[0].split(",");
return "enum";
}
return typeJava;
}
String getVeriabelName(String type){
String name = "";
type = type.toLowerCase();
String[] nameOne = type.split("_");
if(nameOne.length>0){
name += nameOne[0];
for (int i = 1; i < nameOne.length; i++) {
char[] charNames= nameOne[i].toCharArray();
String namePart = (""+charNames[0]).toString().toUpperCase();
for (int j = 1; j < charNames.length; j++) {
namePart+=""+charNames[j];
}
name+=namePart;
}
}
return name;
}
public static void main(String[] args) {
Application.launch(Nera .class, args);
}
}
public class ColumnDAO {
Sql2o sql2o = new Sql2o("jdbc:mysql://localhost:3306/master", "root", "");
public List<ColumnModel> getColumnInfo(String tablename){
String sql = "SHOW COLUMNS FROM "+tablename;
Map<String, String> map = new HashMap();
map.put("Field", "Field");
map.put("Type", "Type");
map.put("Null", "Null");
map.put("Key", "Key");
map.put("Default", "Default");
map.put("Extra", "Extra");
sql2o.setDefaultColumnMappings(map);
try (Connection con = sql2o.open()) {
return con.createQuery(sql)
.executeAndFetch(ColumnModel.class);
}
}
}
public class ColumnModel {
String Field;
String Type;
String Null;
String Key;
String Default;
String Extra;
//getset
}
public class Preference {
public static Map<String, String> map = new HashMap();
static {
map.put("INT", "int");
map.put("TINYINT", "boolean");
map.put("SMALLINT", "int");
map.put("MEDIUMINT", "int");
map.put("BIGINT", "int");
map.put("FLOAT", "double");
map.put("DOUBLE", "double");
map.put("DECIMAL", "double");
map.put("DATE", "Date");
map.put("DATETIME", "Date");
map.put("TIMESTAMP", "Date");
map.put("TIME", "Date");
map.put("YEAR", "Date");
map.put("CHAR", "char");
map.put("VARCHAR", "String");
map.put("BLOB", "String");
map.put("TEXT", "String");
map.put("TINYBLOB", "String");
map.put("TINYTEXT", "String");
map.put("MEDIUMBLOB", "String");
map.put("MEDIUMTEXT", "String");
map.put("LONGBLOB", "String");
map.put("LONGTEXT", "String");
map.put("ENUM", "[enum]");
}
}
---