今天在扩展ibator插件时,在生成model中每个field的注释时,想从oracle数据库中获取每个字段的comments作为注释.使用jdbc的支持,代码如下:
ResultSet rs = (java.sql.DatabaseMetaData)databaseMetaData.getColumns(localCatalog,localSchema,localTableName,null);
while (rs.next()){
rs.getString("REMARKS"));
.............................
java.sql.DatabaseMetaData.getColumns 这个方法从注释就能清楚的看到,可以获取数据库的很多元信息,当然包括表和字段的注释.但是,我获取时,却是NULL.GOOGLE了半天,发现原来oracle是需要在连接JDBC获取connection时通过一个参数来设置是否能获取comments.具体如下:
Properties props =newProperties();
props.put("remarksReporting","true");
Class.forName("oracle.jdbc.driver.OracleDriver");
dbConn = DriverManager.getConnection(url,props);
DatabaseMetaData dbmd = dbConn.getMetaData();
rs = dbmd.getColumns(null,"OPS$AIMSADM","AIRCRAFTS","CODE");
if(rs.next()) {System.out.println("Remarks: "+ rs.getObject(12)); }
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
以上转载。
实际code:
String catalog = dsp.getConnection().getCatalog(); ResultSet tableResult = dsp.getConnection().getMetaData().getTables(catalog,null,null); List<Table> tList = new ArrayList<>(); //获得数据库中的所有表,并将其放入到tList中 while (tableResult.next()) { Table t = new Table(); t.setName(tableResult.getString("TABLE_NAME")); t.setDescription(tableResult.getString("REMARKS")); tList.add(t); }
for (Table table : tableList) { ListIterator<TableType.Column> columnIterator = null; for (TableType tableType : tableTypeList) { if (StringUtils.equals(tableType.getName(),table.getName())) { columnIterator = tableType.getColumn().listIterator(); } } ResultSet colResult = dsp.getConnection().getMetaData().getColumns(null,table.getName(),null); ResultSet pkResult = dsp.getConnection().getMetaData().getPrimaryKeys(null,table.getName()); List<Column> columns = creatOneTableColumns(columnIterator,colResult,pkResult); table.setColumns(columns); tableMap.put(table.getName(),table); }