参考: https://blog.csdn.net/flashdream8/article/details/84237191
https://blog.csdn.net/goxingman/article/details/109506935
通常在mybatis或者mybatisplus中使用所以必须引入的包是
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
只是一个工具类不讲究效率,只讲究能用
直接上代码
数据库字段类型和java字段类型美剧
public enum DataTypeEnum {
SMALLINT("smallint", "java.lang.Integer","Integer"),
MEDIUMINT("mediumint", "java.lang.Integer","Integer"),
INTEGER("integer", "java.lang.Integer","Integer"),
TINYINT("tinyint", "java.lang.Integer","Integer"),
INT("int", "java.lang.Integer","Integer"),
BIGINT("bigint", "java.lang.Long","Long"),
FLOAT("float", "java.lang.Float","Float"),
DOUBLE("double", "java.lang.Double","Double"),
DECIMAL("decimal", "java.math.BigDecimal","BigDecimal"),
DATE("date", "java.util.Date","Date"),
DATETIME("datetime", "java.util.Date","Date"),
TIMESTAMP("timestamp", "java.util.Date","Date"),
TIME("time", "java.util.Date","Date"),
YEAR("year", "java.util.Date","Date"),
CHAR("char", "java.lang.String","String"),
VARCHAR("varchar", "java.lang.String","String"),
BINARY("binary", "byte[]","byte[]"),
VARBINARY("varbinary", "byte[]","byte[]"),
TINYBLOB("tinyblob", "byte[]","byte[]"),
TINYTEXT("tinytext", "java.lang.String","String"),
BLOB("blob", "byte[]","byte[]"),
TEXT("text", "java.lang.String","String"),
MEDIUMBLOB("mediumblob", "byte[]","byte[]"),
MEDIUMTEXT("mediumtext", "java.lang.String","String"),
LONGBLOB("longblob", "byte[]","byte[]"),
LONGTEXT("longtext", "java.lang.String","String"),
ENUM("enum", "java.lang.String","String"),
SET("set", "java.lang.String","String"),
BIT("bit", "java.lang.Boolean","Boolean");
// 成员变量
private String dbType;
private String javaImportType;
private String javaType;
// 构造方法
private DataTypeEnum(String dbType,String javaImportType ,String javaType) {
this.dbType = dbType;
this.javaImportType = javaImportType;
this.javaType = javaType;
}
public static String getJavaType(String dbType) {
for (DataTypeEnum c : DataTypeEnum.values()) {
if (c.getDbType() == dbType) {
return c.javaImportType;
}
}
//找不到就用String 类型
return VARCHAR.javaImportType;
}
public static DataTypeEnum getDataTypeEnumByDbType(String dbType) {
for (DataTypeEnum c : DataTypeEnum.values()) {
if (dbType.equals(c.getDbType())) {
return c ;
}
}
//找不到就用String 类型
return VARCHAR;
}
public String getJavaType() {
return javaType;
}
public String getImportType() {
return javaImportType;
}
public String getDbType() {
return dbType;
}
}
生成文件的工具类
import com.sun.deploy.util.StringUtils;
import lombok.Data;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class DbTableToJavaDoUtils {
@Data
private static class TableRowInfo {
// 属性名称
private String attributeName;
//属性备注
private String attributeComment;
//属性类型
private String attributeType;
//导入类型
private String importType;
}
public static void getTableRowInfo(Connection connection, String tableName) {
List<TableRowInfo> tableRowInfos = new ArrayList<>();
try {
String sql = "show full columns from " + tableName;
Statement st = connection.createStatement();
ResultSet res = st.executeQuery(sql);
while (res.next()) {
TableRowInfo tri = new TableRowInfo();
tri.setAttributeComment(res.getString("Comment"));
tri.setAttributeName(toCamelCase(res.getString("Field")));
DataTypeEnum type = DataTypeEnum.getDataTypeEnumByDbType(res.getString("Type").split("\\(")[0]);
tri.setAttributeType(type.getJavaType());
tri.setImportType(type.getImportType());
tableRowInfos.add(tri);
}
} catch (Exception e) {
e.printStackTrace();
}
createJavaDo(tableRowInfos, tableName);
}
static private void createJavaDo(List<TableRowInfo> tableRowInfo, String tableName) {
Set<String> importSet = new HashSet<>();
StringBuilder attributeTemplate = new StringBuilder();
tableRowInfo.forEach(tabale -> {
//备注
String attributeComment = tabale.getAttributeComment();
// 属性类型
String attributeType = tabale.getAttributeType();
//属性名称
String attributeName = tabale.getAttributeName();
attributeTemplate.append(String.format(" // %s\n private %s %s;\n", attributeComment, attributeType, attributeName));
//需要导入类型
importSet.add("import " + tabale.getImportType() + ";\n");
});
String importTemplate = StringUtils.join(importSet, "");
if(tableName.contains(".")){
tableName = tableName.substring(tableName.indexOf(".")+1);
}
String classLowName = toCamelCase(tableName);
String className = classLowName.substring(0, 1).toUpperCase() + classLowName.substring(1) + "DO";
String classTemplate = String.format("import com.baomidou.mybatisplus.annotation.TableName;\nimport lombok.Data;\n" +
"%s\n\n" +
"@Data\n" +
"@TableName(value = \"%s\")\n" +
"public class %s{\n\n" +
"%s\n" +
"}", importTemplate, tableName, className, attributeTemplate);
createFile(className, classTemplate);
}
private static void createFile(String fileName, String content) {
System.out.println(fileName);
System.out.println(content);
try {
File file = new File(System.getProperty("user.dir") + "\\src\\main\\resources\\" + fileName + ".java");
FileOutputStream fileOutputStream = new FileOutputStream(file);
if (!file.exists()) {
file.createNewFile();
}
byte[] contentInBytes = content.getBytes();
fileOutputStream.write(contentInBytes);
fileOutputStream.flush();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static String toCamelCase(String underlineStr) {
if (underlineStr == null) {
return null;
}
// 分成数组
char[] charArray = underlineStr.toCharArray();
// 判断上次循环的字符是否是"_"
boolean underlineBefore = false;
StringBuffer buffer = new StringBuffer();
for (int i = 0, l = charArray.length; i < l; i++) {
// 判断当前字符是否是"_",如果跳出本次循环
if (charArray[i] == 95) {
underlineBefore = true;
} else if (underlineBefore) {
//如果不是字母 还是用下划线拼接
if(Character.isLowerCase(charArray[i]) || Character.isUpperCase(charArray[i])){
// 如果为true,代表上次的字符是"_",当前字符需要转成大写
buffer.append(charArray[i] -= 32);
underlineBefore = false;
}else{
buffer.append("_"+charArray[i]);
}
} else {
// 不是"_"后的字符就直接追加
buffer.append(charArray[i]);
}
}
return buffer.toString();
}
}
调用代码:
@Autowired
private SqlSession sqlSession;
private static String tableName = "表名"; //当多数据源的时候加上schemas名称
@Test
public void demo3() throws Exception {
Connection connection = sqlSession.getConfiguration().getEnvironment().getDataSource().getConnection();
String tableRowInfo = DbTableToJavaDoUtils.getTableRowInfo(connection, tableName);
}
或者
@Test
public void demo2() throws Exception {
String driverClass = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://127.0.0.1:3306/zhzf_xingzhengfuyi?useUnicode=true&characterEncoding=utf-8";
String userName = "root";
String passWord = "123456";
String tableName = "b_anjianxinxi";
Connection connection = DriverManager.getConnection(url, userName, passWord);
DbTableToJavaDoUtils.getTableRowInfo(connection, tableName);
}
生成的文件在main\resources目录下
我的是MybatisPlus环境