连接mysql数据库后在指定包下生成pojo实体类,dao层,service层,servlet层的简易代码
其中需要配置数据库的相关信息以及配置source root及目标包的绝对路径
运行效果如下,
package utils;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class SqlUtil_2 {
/**
* 数据库配置信息
*/
private static String url = "jdbc:mysql://127.0.0.1:3306/travel?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";
private static String username = "root";
private static String password = "123456";
/**
* 配置蓝色文件夹,即source root的绝对路径
*/
private static String sourceRootAbsolutePath = "D:\\MyProject\\getSqlPojo\\src\\main\\java";
public static void main(String[] args) throws IOException {
SqlUtil_2.buildALL("D:\\MyProject\\getSqlPojo\\src\\main\\java\\com\\dgk\\test");
}
/**
* 表类
*/
static class Table {
/**
* 表名
*/
public String tableName;
/**
* 表中的字段名
*/
public ArrayList<String> colNames;
/**
* 表中的字段类型
*/
public ArrayList<String> colTypes;
/**
* 构造方法
*/
public Table(String tableName) {
this.tableName = tableName;
colNames = new ArrayList<String>();
colTypes = new ArrayList<String>();
}
}
/**
* 连接对象
*/
private static Connection connection;
/**
* sql语句执行对象
*/
private static PreparedStatement preparedStatement;
/**
* 存储表对象的数组
*/
private static ArrayList<Table> tables = new ArrayList<>();
/**
* sql数据类型 : java数据类型
*/
private static Map<String, String> typeMapping = new HashMap<>();
static {
//获取数据库名称
String database = url.split("/")[url.split("/").length-1].split("[?]")[0];
/**
* 此处类型可能不全面,后面根据需要补充
* */
typeMapping.put("INT", "Integer");
typeMapping.put("VARCHAR", "String");
typeMapping.put("DATE", "Date");
typeMapping.put("DECIMAL", "BigDecimal");
typeMapping.put("DOUBLE", "Double");
typeMapping.put("DATETIME", "Timestamp");
try {
/**获取数据库连接对象*/
connection = DriverManager.getConnection(url, username, password);
/**
* 获取结果集元数据
* 获取所有表的名称
* */
DatabaseMetaData metaData = connection.getMetaData();
//System.out.println(metaData.getDatabaseProductName());
ResultSet tableSet = metaData.getTables(database, null, null, new String[]{"TABLE"});
while (tableSet.next()) {
//判断是否为test_db数据库
//if (database.equals(tableSet.getString(1))) {
//添加表名
String tableName = tableSet.getString("TABLE_NAME");
//首字母大写
tableName = tableName.substring(0, 1).toUpperCase() + tableName.substring(1);
tables.add(new Table(tableName));
//}
}
for (Table table : tables) {
String tableName = table.tableName;
preparedStatement = connection.prepareStatement("select * from " + tableName);
//结果集元数据
ResultSetMetaData resultSetMetaData = preparedStatement.getMetaData();
for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
String colName = resultSetMetaData.getColumnName(i);//字段名
String colType = resultSetMetaData.getColumnTypeName(i);//字段类型
colType = typeMapping.get(colType);//转为java数据类型
table.colNames.add(colName);
table.colTypes.add(colType);
}
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
try {
//释放资源
preparedStatement.close();
connection.close();
for (Table table : tables) {
System.out.println("表名:" + table.tableName);
System.out.println("--->字段名:" + table.colNames);
System.out.println("--->字段类型:" + table.colTypes);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
/**
* 构建pojo类
*
* @param absolutePath 构建pojo类的绝对路径
* @throws IOException
*/
public static void buildPojo(String absolutePath) throws IOException {
File pojoFile = new File(absolutePath);
//判断文件夹是否存在
if (!pojoFile.exists()) {
pojoFile.mkdirs();
}
//获取路径
String pojoPath = pojoFile.getAbsolutePath() + "\\";
for (Table table : tables) {
String tableName = table.tableName;
File file = new File(pojoPath + tableName + ".java");
if (!file.exists()) {
file.createNewFile();
FileWriter fileWriter = new FileWriter(file, true);
/**开始写文件*/
/**写入包路径*/
Integer delta = sourceRootAbsolutePath.length();
String packagePath = pojoPath.substring(delta+1);
if (packagePath.contains("\\")) {
packagePath = packagePath.replace("\\", ".");
}
if (packagePath.endsWith(".")) {
packagePath = packagePath.substring(0, packagePath.length() - 1);
}
fileWriter.write("package " + packagePath + ";\n");
/**导包*/
ArrayList<String> colNames = table.colNames;
ArrayList<String> colTypes = table.colTypes;
if (colTypes.contains("BigDecimal")) {
fileWriter.write("import java.math.BigDecimal;\n");
}
if (colTypes.contains("Date")) {
fileWriter.write("import java.util.Date;\n");
}
if (colTypes.contains("Timestamp")) {
fileWriter.write("import java.security.Timestamp;\n");
}
fileWriter.write("public class " + tableName + " {\n");
//填充属性
for (int i = 0; i < colNames.size(); i++) {
fileWriter.write(" private " + colTypes.get(i) + " " + colNames.get(i) + ";\n");
}
//填充getter&setter
for (int i = 0; i < colNames.size(); i++) {
String colName = colNames.get(i);
String colType = colTypes.get(i);
//写入set方法
String set = "set" + colName.substring(0, 1).toUpperCase() + colName.substring(1);
fileWriter.write(" public void " + set + "(" + colType + " " + colName + ") {\n" +
" this." + colName + " = " + colName + ";\n" +
" }\n");
//写入get方法
String get = "get" + colName.substring(0, 1).toUpperCase() + colName.substring(1);
fileWriter.write(" public " + colType + " " + get + "() {\n" +
" return " + colName + ";\n" +
" }\n");
}
//写入toString方法
String str = " @Override\n" +
" public String toString() {\n" +
" return \"" + tableName + "{\" +" + "\n";
for (int i = 0; i < colNames.size(); i++) {
String colName = colNames.get(i);
String colType = colTypes.get(i);
if (i != colNames.size() - 1) {
if ("String".equals(colType)) {
str += " " + "\"" + colName + "='\" + " + colName + " + '\\'' + \",\"+" + "\n";
} else {
str += " " + "\"" + colName + "=\" + " + colName + " + \", \"+" + "\n";
}
continue;
}
if ("String".equals(colType)) {
str += " " + "\"" + colName + "='\" + " + colName + " + '\\''" + "\n";
} else {
str += " " + "\"" + colName + "=\" + " + colName + "\n";
}
}
str += " " + "+'}';\n" + " }\n";
fileWriter.write(str);
fileWriter.write("}");
fileWriter.close();
}
}
}
/**
* 构建接口
*
* @param absolutePath 构建接口的包的绝对路径
* @param addImpl 是否添加实现类
* @throws IOException
*/
public static void buildDao(String absolutePath, Boolean addImpl) throws IOException {
File daoFile = new File(absolutePath);
//判断文件夹是否存在
if (!daoFile.exists()) {
daoFile.mkdirs();
}
//获取路径
String daoPath = daoFile.getAbsolutePath() + "\\";
for (Table table : tables) {
String tableName = table.tableName;
File file = new File(daoPath + tableName + "Dao.java");
if (!file.exists()) {
file.createNewFile();
FileWriter fileWriter = new FileWriter(file, true);
/**开始写文件*/
/**写入包路径*/
Integer delta = sourceRootAbsolutePath.length();
String packagePath = daoPath.substring(delta+1);
if (packagePath.contains("\\")) {
packagePath = packagePath.replace("\\", ".");
}
if (packagePath.endsWith(".")) {
packagePath = packagePath.substring(0, packagePath.length() - 1);
}
fileWriter.write("package " + packagePath + ";\n");
/**写接口*/
fileWriter.write("public interface " + tableName + "Dao {\n");
fileWriter.write(" \n");
fileWriter.write("}");
fileWriter.close();
}
}
/**添加实现类*/
if (addImpl) {
String daoImplPath = daoPath + "impl\\";
File mapperImplFile = new File(daoImplPath);
//判断文件夹是否存在
if (!mapperImplFile.exists()) {
mapperImplFile.mkdirs();
}
for (Table table : tables) {
String tableName = table.tableName;
File file = new File(daoImplPath + tableName + "DaoImpl.java");
if (!file.exists()) {
file.createNewFile();
FileWriter fileWriter = new FileWriter(file, true);
/**开始写文件*/
/**写入包路径*/
String packagePath = daoImplPath.split("java\\\\")[1];
if (packagePath.contains("\\")) {
packagePath = packagePath.replace("\\", ".");
}
if (packagePath.endsWith(".")) {
packagePath = packagePath.substring(0, packagePath.length() - 1);
}
fileWriter.write("package " + packagePath + ";\n");
/**导包*/
fileWriter.write("import " + packagePath.split("impl")[0] + "" + tableName + "Dao;\n");
/**写接口*/
fileWriter.write("public class " + tableName + "DaoImpl implements " + tableName + "Dao {\n");
fileWriter.write(" \n");
fileWriter.write("}");
fileWriter.close();
}
}
}
}
/**
* 构建service,若需要实现类则要传入daoImplPackageAbsolutePath,不需要impl则传入null
*
* @param absolutePath service包的绝对路径
* @param daoPackageAbsolutePath dao包的绝对路径
* @throws IOException
*/
public static void buildService(String absolutePath, String daoPackageAbsolutePath) throws IOException {
File serviceFile = new File(absolutePath);
//判断文件夹是否存在
if (!serviceFile.exists()) {
serviceFile.mkdirs();
}
//获取路径
String servicePath = serviceFile.getAbsolutePath() + "\\";
for (Table table : tables) {
String tableName = table.tableName;
File file = new File(servicePath + tableName + "Service.java");
if (!file.exists()) {
file.createNewFile();
FileWriter fileWriter = new FileWriter(file, true);
/**开始写文件*/
/**写入包路径*/
Integer delta = sourceRootAbsolutePath.length();
String packagePath = servicePath.substring(delta+1);
if (packagePath.contains("\\")) {
packagePath = packagePath.replace("\\", ".");
}
if (packagePath.endsWith(".")) {
packagePath = packagePath.substring(0, packagePath.length() - 1);
}
fileWriter.write("package " + packagePath + ";\n");
/**写接口*/
fileWriter.write("public interface " + tableName + "Service {\n");
fileWriter.write(" \n");
fileWriter.write("}");
fileWriter.close();
}
}
/**添加实现类*/
if (null != daoPackageAbsolutePath && 0 < daoPackageAbsolutePath.length()) {
String serviceImplPath = servicePath + "impl\\";
File serviceImplFile = new File(serviceImplPath);
//判断文件夹是否存在
if (!serviceImplFile.exists()) {
serviceImplFile.mkdirs();
}
for (Table table : tables) {
String tableName = table.tableName;
File file = new File(serviceImplPath + tableName + "ServiceImpl.java");
if (!file.exists()) {
file.createNewFile();
FileWriter fileWriter = new FileWriter(file, true);
/**开始写文件*/
/**写入包路径*/
String packagePath = serviceImplPath.split("java\\\\")[1];
if (packagePath.contains("\\")) {
packagePath = packagePath.replace("\\", ".");
}
if (packagePath.endsWith(".")) {
packagePath = packagePath.substring(0, packagePath.length() - 1);
}
fileWriter.write("package " + packagePath + ";\n");
/**导包*/
fileWriter.write("import " + packagePath.split("impl")[0] + "" + tableName + "Service;\n");
/**
* 此处应该导入dao实现类的包,但是
*/
String daoPath = daoPackageAbsolutePath.split("java\\\\")[1];
if (daoPath.contains("\\")) {
daoPath = daoPath.replace("\\", ".");
}
if (daoPath.endsWith(".")) {
daoPath = daoPath.substring(0, daoPath.length() - 1);
}
//接口
fileWriter.write("import " + daoPath + "." + tableName + "Dao;\n");
//实现类
fileWriter.write("import " + daoPath + ".impl." + tableName + "DaoImpl;\n");
/**写实现*/
fileWriter.write("public class " + tableName + "ServiceImpl implements " + tableName + "Service {\n");
String tableLowerName = tableName.substring(0, 1).toLowerCase() + tableName.substring(1);
fileWriter.write("private " + tableName + "Dao " + tableLowerName + "Dao = new " + tableName + "DaoImpl();\n");
fileWriter.write(" \n");
fileWriter.write("}");
fileWriter.close();
}
}
}
}
/**
* 构建servlet(继承BaseServlet)
* @param absolutePath servlet包的绝对路径
* @param servicePackageAbsolutePath service包的绝对路径
* @throws IOException
*/
public static void buildServlet(String absolutePath, String servicePackageAbsolutePath)throws IOException{
File servletFile = new File(absolutePath);
//判断文件夹是否存在
if (!servletFile.exists()) {
servletFile.mkdirs();
}
//获取路径
String servletPath = servletFile.getAbsolutePath() + "\\";
/**获取包路径*/
Integer delta = sourceRootAbsolutePath.length();
String packagePath = servletPath.substring(delta+1);
if (packagePath.contains("\\")) {
packagePath = packagePath.replace("\\", ".");
}
if (packagePath.endsWith(".")) {
packagePath = packagePath.substring(0, packagePath.length() - 1);
}
for (Table table : tables) {
String tableName = table.tableName;
File file = new File(servletPath + tableName + "Servlet.java");
if (!file.exists()) {
file.createNewFile();
FileWriter fileWriter = new FileWriter(file, true);
/**开始写文件*/
/**导包*/
fileWriter.write("package " + packagePath + ";\n");
String servicePath = servicePackageAbsolutePath.split("java\\\\")[1];
if (servicePath.contains("\\")) {
servicePath = servicePath.replace("\\", ".");
}
if (servicePath.endsWith(".")) {
servicePath = servicePath.substring(0, servicePath.length() - 1);
}
//接口
fileWriter.write("import " + servicePath + "." + tableName + "Service;\n");
//实现类
fileWriter.write("import " + servicePath + ".impl." + tableName + "ServiceImpl;\n");
fileWriter.write("import javax.servlet.annotation.WebServlet;\n");
String tableLowerName = tableName.substring(0, 1).toLowerCase() + tableName.substring(1);
fileWriter.write("@WebServlet(\"/"+tableLowerName+"/*\")\n");
fileWriter.write("public class "+tableName+"Servlet extends BaseServlet{\n");
fileWriter.write("private "+tableName+"Service "+tableLowerName+"Service = new "+tableName+"ServiceImpl();\n");
fileWriter.write(" \n");
fileWriter.write("}");
fileWriter.close();
}
}
//构建baseServlet
File file = new File(servletPath + "BaseServlet.java");
if (!file.exists()) {
file.createNewFile();
FileWriter fileWriter = new FileWriter(file, true);
/**开始写文件*/
/**导包*/
fileWriter.write("package " + packagePath + ";\n");
fileWriter.write("import javax.servlet.ServletException;\n" +
"import javax.servlet.http.HttpServlet;\n" +
"import javax.servlet.http.HttpServletRequest;\n" +
"import javax.servlet.http.HttpServletResponse;\n" +
"import java.io.IOException;\n" +
"import java.lang.reflect.InvocationTargetException;\n" +
"import java.lang.reflect.Method;\n" +
"\n" +
"/**\n" +
" * @Author: dgk1024\n" +
" * @Date: 2020/7/23-17:01\n" +
" * @Description: 在这完成方法的分发\n" +
" */\n" +
"//不需要被访问到\n" +
"public class BaseServlet extends HttpServlet {\n" +
" @Override\n" +
" protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n" +
" /**\n" +
" * 方法的分发:\n" +
" * 1. 获取请求的路径\n" +
" * 2. 获取方法的名称\n" +
" * 3. 获取方法对象Method\n" +
" * 4. 执行方法\n" +
" * (利用了反射相关知识)\n" +
" */\n" +
" //获取请求参数\n" +
" String uri =request.getRequestURI();\n" +
" //获取方法名称\n" +
" String methodName = uri.substring(uri.lastIndexOf(\"/\")+1);\n" +
" try {\n" +
" //获取执行方法class对象\n" +
" //Method getMethod(String name,类<?>...parameterTypes)\n" +
" Method method = this.getClass().getMethod(\n" +
" methodName,\n" +
" HttpServletRequest.class,\n" +
" HttpServletResponse.class\n" +
" );\n" +
" //谁调用BaseServlet,BaseServlet代表谁\n" +
" method.invoke(\n" +
" this,\n" +
" request,\n" +
" response\n" +
" );\n" +
" } catch (IllegalAccessException e) {\n" +
" e.printStackTrace();\n" +
" } catch (InvocationTargetException e) {\n" +
" e.printStackTrace();\n" +
" } catch (NoSuchMethodException e) {\n" +
" e.printStackTrace();\n" +
" }\n" +
" }\n" +
"}");
fileWriter.close();
}
}
/**
* 给定一个包的绝对路径,在当前包下生成pojo包,service包,servlet包
* @param basePackageAbsolutePath
* @throws IOException
*/
public static void buildALL(String basePackageAbsolutePath) throws IOException {
String pojoPath = basePackageAbsolutePath + "\\pojo";
buildPojo(pojoPath);
String daoPath = basePackageAbsolutePath + "\\dao";
buildDao(daoPath, true);
String servicePath = basePackageAbsolutePath + "\\service";
buildService(servicePath, daoPath);
String servletPath = basePackageAbsolutePath + "\\servlet";
buildServlet(servletPath, servicePath);
}
public static void buildMapperXml(String absolutePath) {
File mapperFile = new File(absolutePath);
//判断文件夹是否存在
if (!mapperFile.exists()) {
mapperFile.mkdirs();
}
}
}