My question is similar to the one asked here: http://forum.springsource.org/showthread.php?84508-jdbctemplate.query()-sorted-result-set but a clear answer was not provided - an ArrayList
does not guarantee order.
Basically, I would like to know if the call returned by jdbcTemplate.query()
guarantees the order of the resultset and if I can dump it into a LinkedList
and pass it along :)
Thanks!
Edit: I should clarify that the query does include an order by
clause, hence my requirements for a resultset that guarantees order. I was incorrect regarding the ArrayList
not doing so. Since the jdbcTemplate is an interface the implementation would depend upon the db library. Should I make the assumption that an ArrayList
will be used or sort it again to be on the safe side?
The JdbcTemplate class executes SQL queries, update statements and stored procedure calls, performs iteration over ResultSet s and extraction of returned parameter values. It also catches JDBC exceptions and translates them to the generic, more informative, exception hierarchy defined in the org. springframework.
ResultSetExtractor interface is a callback interface used by JdbcTemplate's query methods. Implementations of this interface perform the actual work of extracting results from a ResultSet, but don't need to worry about exception handling. SQLExceptions will be caught and handled by the calling JdbcTemplate.
The JdbcTemplate query method accepts a string containing your SQL query and a RowMapper to make this possible. The SQL string contains a query to select all the records from the database and the RowMapper maps each of the records to an employee object using the method you have implemented above.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With