简体   繁体   English

如何获取列表<object[]>来自使用 Spring Jdbc 的查询</object[]>

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

I use Spring Jdbc for queries.我使用 Spring Jdbc 进行查询。 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[]> .我需要从数据库中执行 select ,但我不知道要从结果集中获取结果的表中有多少列(例如,对于RowMapper )。我想获取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:如果您手头有ResultSet ,则可以使用元数据查看结果:

ResultSetMetaData metaData = resultSet.getMetaData();

Then you can get a column count with metaData.getColumnCount() , and poke at specific ones with various methods like this:然后,您可以使用metaData.getColumnCount()获取列数,并使用以下各种方法查看特定的列数:

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;如果您有 static model 类与静态类型字段,整齐 map 到您的结果集,那么您的生活会更轻松; and if you do this, you can even skip jdbc alltoghter and let Spring Data all the query and Resultset mapping work.如果你这样做,你甚至可以跳过 jdbc alltoghter,让 Spring Data 所有查询和结果集映射工作。

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. 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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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