#2025上海国际车展#
package com.alatus.builder;
import com.alatus.Entity.TableInfo;
import com.alatus.constant.Constants;
import com.alatus.utils.PropertiesUtils;
import com.alatus.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class TableBuilder {
private static Connection CONNECTION = null;
private static Logger LOGGER = LoggerFactory.getLogger(TableBuilder.class);
private static String SHOW_TABLE_STATUS = "show table status";
static{
String driverName = PropertiesUtils.getValue("db.driver.name");
String url = PropertiesUtils.getValue("db.url");
String username = PropertiesUtils.getValue("db.username");
String password = PropertiesUtils.getValue("db.password");
try {
Class.forName(driverName);
CONNECTION = DriverManager.getConnection(url, username, password);
LOGGER.info("数据库连接成功");
} catch (ClassNotFoundException e) {
LOGGER.error("数据库驱动加载失败");
throw new RuntimeException(e);
} catch (SQLException e) {
LOGGER.error("数据库连接失败");
throw new RuntimeException(e);
}
}
public static void getTables(){
PreparedStatement preparedStatement = null;
ResultSet results = null;
List<TableInfo> tableInfoList = new ArrayList<>();
try{
preparedStatement = CONNECTION.prepareStatement(SHOW_TABLE_STATUS);
results = preparedStatement.executeQuery();
while(results.next()){
String tableName = results.getString("name");
String comment = results.getString("comment");
LOGGER.info("表名:{},注释:{}",tableName,comment);
TableInfo tableInfo = new TableInfo();
tableInfo.setTableName(tableName);
tableInfo.setComment(comment);
String beanName = tableName;
if(Constants.IGNORE_TABLE_PREFIX){
beanName = tableName.substring(tableName.indexOf("_")+1);
}
beanName = processFields(beanName,true);
LOGGER.info("bean名称:{}",beanName);
}
}
catch (SQLException e){
LOGGER.error("获取表失败");
}
finally {
LOGGER.info("关闭数据库连接");
if(preparedStatement!=null){
try {
preparedStatement.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if(results!=null){
try {
results.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if (CONNECTION != null){
try {
CONNECTION.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
}
private static String processFields(String fieldName,Boolean upperCase){
StringBuilder builder = new StringBuilder();
String[] fields = fieldName.split("_");
builder.append(upperCase? StringUtils.firstCharToUpperCase(fields[0]):fields[0]);
for (int i = 1; i < fields.length; i++) {
builder.append(StringUtils.firstCharToUpperCase(fields[i]));
}
return builder.toString();
}
}