根据表结构自动生产实体类和方法,根据反射与io生成,可自定义扩展方法
package com.digital.web.front; /**
* pom依赖
*
* mysql
* mysql-connector-java
* 5.1.27
*
*
* org.projectlombok
* lombok
* 1.16.10
*
*/
import com.alibaba.fastjson.JSONObject;
import com.mchange.v2.collection.MapEntry;
import lombok.Data;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.*;
import java.util.*;
/**
* 自定义框架
* 生成mysql表对应的实体类
*/
public class MySqlMapper {
/**
* 配制参数
*/
static class Config {//mysql地址,数据库,用户名,密码
final static private String address = "12.0.0.1:3306";
final static private String dbName = "henan";
final static private String username = "root";
final static private String password = "12346";
//模型保存的位置
final static private String modelPath = "G:\\IdeaProject\\中文\\src\\main\\java\\com\\digital\\web\\front\\model";
//mysql数据类型与java数据类型转换
final static MapEntry[] map = {
new MapEntry("INT", "Integer"),
new MapEntry("VARCHAR", "String"),
new MapEntry("TIMESTAMP", "String"),
new MapEntry("DOUBLE", "Double")
};
}
/**
* 内存参数
*/
static class Variable {
final static private String packagePath = Config.modelPath.split("java\\\\")[1].replace("\\", ".");
static private Map mapper = new HashMap<>();
static {
for (MapEntry mapEntry : Config.map) {
mapper.put(String.valueOf(mapEntry.getKey()), String.valueOf(mapEntry.getValue()));
}
}
}
/**
* 获取连接
*
* @return
* @throws SQLException
* @throws ClassNotFoundException
*/
public static Connection getConn() throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://" + Config.address + "/" + Config.dbName + "?useUnicode=true&characterEncoding=UTF-8";
Connection conn = DriverManager.getConnection(url, Config.username, Config.password);
return conn;
}
public static void main(String[] args) throws Exception {
Connection conn = getConn();
List modelTableList = Business.getModelTable(conn);//获取数据库下的表结构
conn.close();
Business.foreach(modelTableList);//遍历结构数据
}
static class Business {//业务类
/**
* 获取数据库中表与字段的集合
*
* @param conn
* @return
*/
public static List getModelTable(Connection conn) throws Exception {
List modelTableList = new LinkedList<>();
Map tableMsg = Business.getTableNameList(conn);
for (Map.Entry line : tableMsg.entrySet()) {
ModelTable tableFieldMap = getTableFieldMap(conn, line);
modelTableList.add(tableFieldMap);
}
return modelTableList;
}
/**
* 获取表名称
*
* @param conn
* @return
* @throws Exception
*/
public static Map getTableNameList(Connection conn) throws Exception {
String sql = "select TABLE_NAME,TABLE_COMMENT from information_schema.tables where table_schema=\"henan\"";
List