简体   繁体   中英

How to get List<Object[]> from a query using Spring Jdbc

I use Spring Jdbc for queries. I need to execute select from the database, but I don't know how many columns in the table to get the result from resultset (for example, for RowMapper ).I would like to get List<Object[]> . Is it possible? And how can I get data without knowing the number of columns in the database?

If you have a ResultSet at hand, you can look into the result using metadata:

ResultSetMetaData metaData = resultSet.getMetaData();

Then you can get a column count with metaData.getColumnCount() , and poke at specific ones with various methods like this:

int count = metaData.getColumnCount();
for (int i = 1; i <= count; i++) { // yeah, sql indexes from 1
    System.out.println(metaData.getColumnName(i));
    System.out.println(metaData.isNullable(i));
    //... see ResultSetMetadata JavaDoc for the rest
}

If you want a List as the result, you should definitely question your conceptual approach for what you are trying to achieve. Ask yourself if you really can't or don't want to know in advance what colums you will receive, and how will you handle the unknown types of these columns? You would make your life way easier if you have static model classes with statically typed fields that neatly map to your result set; and if you do this, you can even skip jdbc alltoghter and let Spring Data all the query and Resultset mapping work.

But if this really is not an option for you, then at least don't map your result rows to an Object array, but rather to simple JSON objector a Map, unless you don't care much about what value belonged to what column.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM