java自动生成代码

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

1.与数据库建立连接

在DBUtil中设置数据库相关的参数

Class.forName(driverName);

conn = DriverManager.getConnection(url, user, password);

2.获得数据库中的所有表

Mapmaps = new HashMap();

PreparedStatement pstate = conn.prepareStatement("show table status"); ResultSet results = pstate.executeQuery();

while (results.next()) {

String tableName = results.getString("NAME");

String comment = results.getString("COMMENT");

maps.put(tableName, comment);

}

3.获得每个表中的信息

封装一个实体来存储表中的信息

PreparedStatement pstate = conn.prepareStatement("show full fields from " + tableName);

ResultSet results = pstate.executeQuery();

List lists = new ArrayList();

while (results.next()) {

Column column = new Column();

String field = results.getString("FIELD");

column.setFeildMapper(field);

String fieldName = processField(field);

column.setFeild(fieldName);

String type = processType(results.getString("TYPE"));

String comment = results.getString("COMMENT");

column.setType(type);

column.setComment(comment);

lists.add(column);

}

4.拼串输出

将固定代码中需要变动的字段从实体中取拼串写入文档中

例如给表生成po:

public class WritePo {

public static void createPo(String path,String packageName,String upTable, String lowTable, List columns) throws IOException {

File folder = new File(path + lowTable + "/po");

if (!folder.exists()) {

folder.mkdirs();

}

File beanFile = new File(folder + "/" + upTable + ".java");

BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(

new FileOutputStream(beanFile)));

bw.write("package "+packageName+lowTable+".po;");

bw.write("import java.io.Serializable;");

bw.newLine();

// bw.write("import lombok.Data;");

// bw.write("import javax.persistence.Entity;");

bw.newLine();

bw.write("@SuppressWarnings(\"serial\")");

bw.newLine();

// bw.write("@Entity");

// bw.write("@Data");

// bw.newLine();

bw.write("public class " + upTable + " implements Serializable {"); bw.newLine();

bw.newLine();

int size = columns.size();

for (Column vo : columns) {

// bw.write("\t/**" + comments.get(i) + "**/");

bw.write("\t/**");

bw.newLine();

bw.write("\t *" + vo.getComment());

bw.write("\t **/");

bw.newLine();

bw.write("\tprivate " + vo.getType() + " " + vo.getFeild() + ";"); bw.newLine();

bw.newLine();

}

bw.newLine();

// 生成get 和set方法

String tempField = null;

String _tempField = null;

String tempType = null;

for (Column vo : columns) {

tempType = vo.getType();

_tempField = vo.getFeild();

tempField = _tempField.substring(0, 1).toUpperCase()

+ _tempField.substring(1);

bw.newLine();

// bw.write("\tpublic void set" + tempField + "(" + tempType + " _" + // _tempField + "){");

相关文档
最新文档