5

私の質問は、ここで尋ねられたものと似ています: http://forum.springsource.org/showthread.php?84508-jdbctemplate.query()-sorted-result-setしかし、明確な答えは提供されませんでした - はArrayList順序を保証しません.

jdbcTemplate.query()基本的に、返された呼び出しが結果セットの順序を保証するかどうか、およびそれを a にダンプして渡すことができるかどうかを知りたいLinkedList:)

ありがとう!

編集:クエリに句が含まれていることを明確にするorder by必要があるため、順序を保証する結果セットの要件です。そうしないことに関して私は間違っArrayListていました。jdbcTemplate はインターフェイスであるため、実装は db ライブラリに依存します。が使用されると仮定するArrayListか、安全のために再度ソートする必要がありますか?

4

3 に答える 3

6

an ArrayList does not guarantee order.

This is just wrong. An ArrayList does guarantee order. It has a get(int index) method which can be used to retrieve an element from the specified 0-based index. The add(T item) method will add them in sequence to the list. You may be confusing the List collection type with the Set interface, which is similar to a List except for it does not guarantee order.

That said, it does not actually answer your question...

The ResultSet, without a specified ordering, will return the data in the table's natural order. This is usually based of of the PK field(s) but this is not true for all DBMSs.

If order is important, specify it to be certain. Even if it comes back in the desired order now, changes to the DB schema might affect this later and break assumptions made by your code. Being explicit is better, and will express the code's intent clearer.

Update from edit to question: If an order by is specified in the query, you can rely 100% on the order of the result set. No need to sort it again.

于 2011-06-07T19:15:07.327 に答える
2

これはあなたの質問に答えていますか?

public List<T> extractData(ResultSet rs) throws SQLException {
    List<T> results = (this.rowsExpected > 0 ? new ArrayList<T>(this.rowsExpected) : new ArrayList<T>());
    int rowNum = 0;
    while (rs.next()) {
        results.add(this.rowMapper.mapRow(rs, rowNum++));
    }
    return results;
}

RowMapperResultSetExtractorから。このクラスは、 のいくつかのquery()メソッドで使用されJdbcTemplateます。

結果セット レコードを混合する場所がありません。実際、結果セットは、完全なコレクションというよりもイテレータまたはストリームに似ています。これは、結果セットから事前にすべてのレコードをロードする必要があるため、順序を変更するのは非常に非効率的であることを意味します。

于 2011-06-07T19:22:07.383 に答える