How to retrieve column names from a specific SQL table? There are two options: either fiddling with the poor JDBC API (ResultSetMetadata
and friends) or using a hidden gem from Spring API: TableMetaDataContext
.
We need just two classes:
- a
DataSource
that providesjava.sql.Connection
. - a
org.springframework.jdbc.core.metadata.TableMetaDataContext
which will provide the table metadata.
First, let’s configure the datasource the usual way:
MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setUrl("jdbc:mysql://localhost/dragon");
dataSource.setUser("dragon");
dataSource.setPassword("dragon");
Then, we create the table metadata context, set the table name and call the processMetadata()
method, where we specify the datasource. Two other parameters are not important now. They are used from other internal Spring classes to resolve upper and lowercase column names, or to specify primary key columns, which does not concern us.
TableMetaDataContext tableMetadataContext = new TableMetaDataContext();
tableMetadataContext.setTableName("hero");
tableMetadataContext.processMetaData(dataSource, Collections.<String>emptyList(), new String[0]);
System.out.println(tableMetadataContext.getTableColumns());
And we’re done!