Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get list of all table names from spring SimpleJdbcTemplate

Is there a way to obtain the list of all table names in the database using Spring's SimpleJdbcTemplate?

The database being queried is Oracle if that helps in any way. Thanks.

like image 961
niran Avatar asked Nov 23 '09 01:11

niran


3 Answers

You're always free to get java.sql.DatabaseMetaData using the Connection. There aren't any methods in SimpleJdbcTemplate to help you, but frankly there's no need.

DatabaseMetaData md = c.getMetaData();
ResultSet rs = md.getTables(null, null, "%", null);
while (rs.next()) {
  System.out.println(rs.getString("TABLE_NAME"));
}
like image 85
duffymo Avatar answered Nov 04 '22 22:11

duffymo


Spring has a DatabaseMetaDataCallback object that can take care of some of the boiler plate aspects of the solution that duffymo has linked to. You can then pass that object when calling JDBCUtils.extractDatabaseMetaData.

An example of making the same call you're trying to make with those classes can be found here.

Sample code from that link:

Class:

class GetTableNames implements DatabaseMetaDataCallback {

        public Object processMetaData(DatabaseMetaData dbmd) throws SQLException {
            ResultSet rs = dbmd.getTables(dbmd.getUserName(), null, null, new String[]{"TABLE"});
            ArrayList l = new ArrayList();
            while (rs.next()) {
                l.add(rs.getString(3));
            }
            return l;
        }
    }

Usage:

GetTableNames getTableNames = new GetTableNames();
try {
    Object o = JdbcUtils.extractDatabaseMetaData(dataSource, getTableNames);
    System.out.println(o);
} catch (MetaDataAccessException e) {
    System.out.println(e);
}
like image 32
Jason Gritman Avatar answered Nov 04 '22 23:11

Jason Gritman


Query the USER_TABLES view and you will get them.

poke around in sqlplus, of course, to see the shape first.

like image 41
bmargulies Avatar answered Nov 04 '22 21:11

bmargulies