Project combat, through the class object, attribute information such as the reflective type. Through the database connection information, access to all the objects and results

Demand is still in the project: mysql operations carried out based on, because as a generic product model, docking different cities, it is not determined mapper is available. Therefore, using jdbc to be packaged.

scene one:

Conditions: The database has a plug IDEA, POJO generated using a corresponding entity class.

Requirements: Get all the table of contents (select *), list output.

  

public static final String ENTRY_PATH = "com.ucap.exchange.dataexchange.entity";
    public static List<ComplexResults> getData(Connection conn) {

    //获取实体类包路径 String packageName
= ENTRY_PATH;
    // Set
<String> classNames = getClassName(packageName, false); List<ComplexResults> resultList = new ArrayList(); for (String className : classNames) { String tableName = className.substring(className.lastIndexOf(".") + 1); String sql = "select * from " + tableName ; try { Class tableNameClass = Class.forName(className); List fserd = queryToObj(tableNameClass, conn, sql); for (Object obj : fserd) { ComplexResults complexResults = new ComplexResults(null, tableName, System.currentTimeMillis(), ExchangeConstants.INSERT, obj, null); resultList.add(complexResults); } } catch (Exception e) { e.printStackTrace(); } } return resultList; }
/ ** 
generic * @param <T> object package
* @param clazz entity class object
* @param sql sql statement
* @return List
* /
public static <T> List <T> queryToObj (Class <T> clazz, Conn Connection, String SQL) {
the try {
// Get the result set 1.
the PreparedStatement conn.prepareStatement PS = (SQL);
the resultSet ps.executeQuery RS = ();

results of the query field name // 2. get all of the acquired field
the ResultSetMetaData rs.getMetaData the metaData = ();

// save the objects to
the ArrayList <T> cols = new new the ArrayList <> ();
the while (rs.next ()) {
// create the object
T obj = clazz.newInstance ( );
for (int I =. 1; I <= metaData.getColumnCount (); I ++) {
// 通过反射获取对应的字段
Field filed = clazz.getDeclaredField(metaData.getColumnLabel(i).toLowerCase());
filed.setAccessible(true);
Object value = rs.getObject(metaData.getColumnLabel(i));
filed.set(obj, value);
}
cols.add(obj);
}
return cols;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
 
 
/**
* 获取某包下所有类
*
* @param packageName 包名
* @param isRecursion 是否遍历子包
* @return 类的完整名称
*/
public static Set<String> getClassName(String packageName, boolean isRecursion) {
Set<String> classNames = null;
ClassLoader loader = Thread.currentThread().getContextClassLoader();
String packagePath = packageName.replace(".", "/");

URL url = loader.getResource(packagePath);
if (url != null) {
String protocol = url.getProtocol();
if (protocol.equals("file")) {
classNames = getClassNameFromDir(url.getPath(), packageName, isRecursion);
} else if (protocol.equals("jar")) {
JarFile jarFile = null;
try {
jarFile = ((JarURLConnection) url.openConnection()).getJarFile();
} catch (Exception e) {
e.printStackTrace();
}

if (jarFile != null) {
getClassNameFromJar(jarFile.entries(), packageName, isRecursion);
}
}
} else {
/*从所有的jar包中查找包名*/
classNames = getClassNameFromJars(((URLClassLoader) loader).getURLs(), packageName, isRecursion);
}

return classNames;
}
 
ComplexResults I is a result set object encapsulation, explicit write a constructor, when the new object is generated with the instances.
queryToObj method, obtaining the results according to the getMetaData sql query result set (), and then acquires the corresponding key field by reflecting, using sql result set Set.getObject (key), to obtain the value, the result returned package.
getClassName method, based on the packet path to acquire a corresponding entity object set into the collection bag.

Scene 2: optimized version. (Minus the binding entity classes)

Conditions: existing database connection, dynamic scanning table structure. No entity class.

Requirements: Get all the table of contents (select *), list output.

  public static final String EXCLUDE_TABLE = "sys_datachange_log";
  public  static List <ComplexResults> the getData (Connection Conn) throws SQLException { 

        the DatabaseMetaData DBMD = conn.getMetaData ();
 //         get all tables
      
      // Get database instance String Catalog = conn.getCatalog (); List <String> = stringList new new the ArrayList <> ();
      // get the list of all objects the ResultSet tableRet
= DBMD.getTables (Catalog, null , null , new new String [] { "tABLE" }); the while (tableRet.next ()) { stringList.add (tableRet .getString ("TABLE_NAME")); } List<ComplexResults> resultList = new ArrayList(); for (String m_TableName : stringList) { if (!EXCLUDE_TABLE.equals(m_TableName)) { String columnName; String columnType_Sql; String columnType_Java;
          //获取表内的列,属性等信息 ResultSet colRet
= dbmd.getColumns(catalog, "%", m_TableName, "%"); Map sqlResultsMap = new HashMap(); while (colRet.next()) { columnName = colRet.getString("COLUMN_NAME"); columnType_Sql = colRet.getString("TYPE_NAME"); sqlResultsMap.put(columnName,columnType_Sql); } String sql = "select * from " + m_TableName; List<Entity> entityList = SqlExecutor.query(conn, sql, new EntityListHandler()); for (Entity entity : entityList) { ComplexResults complexResults = new ComplexResults(null, m_TableName, System.currentTimeMillis(), ExchangeConstants.INSERT, entity, sqlResultsMap); resultList.add(complexResults); } } } return resultList; }

 

EXCLUDE_TABLE This table is a log table, you do not need to get content. 
Rational use some method in the java.sql package.
Write a second to realize, I had corrected the result set objects ComplexResults class, so that the logic behind the more convenient to use.
 

Guess you like

Origin www.cnblogs.com/justtodo/p/11990759.html