Spring and retrieving SQL table column names

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:

First, let’s configure the datasource the usual way:

    MysqlDataSource dataSource = new MysqlDataSource();

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.processMetaData(dataSource, Collections.<String>emptyList(), new String[0]);


And we’re done!

Pridaj komentár

Vaša e-mailová adresa nebude zverejnená. Vyžadované polia sú označené *