wiki.xsx.jg.core.CommonService Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of JG-All Show documentation
Show all versions of JG-All Show documentation
a generator, from the database tables convert to the Java classes or from the Java classes convert to the database tables.
support mysql, oracle, sqlserver and postgresql.
package wiki.xsx.jg.core;
import wiki.xsx.jg.log.Logger;
import java.sql.*;
import java.util.*;
/**
* 通用数据库实现类
*/
public class CommonService{
/**
* 根据表名称获取数据表字段及类型
* @param tableNames 表名称
* @param service 数据库服务实现类
* @return 返回字段及类型map集合
* @throws SQLException 异常信息
*/
public static Map>> getTableInfo(
String tableNames,
DatabaseService service
) throws SQLException {
System.setProperty("jdbc.drivers", service.getDriverClassName());
try (
Connection connection = DriverManager.getConnection(service.getDbUrl(), service.getDbUserName(), service.getDbPassword());
PreparedStatement statement = connection.prepareStatement(service.testQuery())
){
Map>> tableMap = new HashMap<>();
List tableList = new ArrayList<>();
if (tableNames==null||tableNames.trim().length()==0){
ResultSet result = statement.executeQuery(service.getAllTableSQL());
while (result.next()){
tableList.add(result.getString(1).toLowerCase());
}
result.close();
}else{
tableList.addAll(getTableList(tableNames));
}
for (String tableName : tableList){
ResultSet result = statement.executeQuery(service.getTableStructureSQL(tableName));
ResultSetMetaData metaData = result.getMetaData();
Map> data = new HashMap<>();
for (int i=1;i<=metaData.getColumnCount();i++){
data.put(metaData.getColumnName(i).toLowerCase(), service.getTypeClass(metaData.getColumnTypeName(i), metaData.getPrecision(i), metaData.getScale(i)));
}
tableMap.put(tableName, data);
result.close();
}
return tableMap;
}catch (SQLException e){
throw e;
}
}
/**
* 根据类名称及其属性创建数据表
* @param classInfoMap 类名称及其属性集合
* @param service 数据库服务实现类
* @throws SQLException 异常信息
*/
public static void createTables(
Map>>>> classInfoMap,
DatabaseService service
) throws SQLException {
System.setProperty("jdbc.drivers", service.getDriverClassName());
try (
Connection connection = DriverManager.getConnection(service.getDbUrl(), service.getDbUserName(), service.getDbPassword());
PreparedStatement statement = connection.prepareStatement(service.testQuery())
){
for (Map.Entry>>>> classInfo : classInfoMap.entrySet()){
StringBuilder className = new StringBuilder(classInfo.getKey());
Map>>> fieldMap = classInfo.getValue();
List