views:

55

answers:

3

Hello. How to Sort DB records in DB table with JdbcTemplate?

What is the best solution, should execute method be used?

+2  A: 

JdbcTemplate simply executes the SQL that you provide to it in the execute method, so use the standard SQL method: ORDER BY

scompt.com
so if i want to sort table by column1,expression should looks like :jdbcTemplate.execute("select * from MyTable ORDER BY column1 ASC"?or what method instead of execute?
sergionni
Yes, that's correct. The ordering should be done by the database in your SQL query. The correct way to execute queries using `JdbcTemplate` is the `execute` method.
scompt.com
+1  A: 

There are a couple ways, though the JdbcTemplate is incidental to them. The first would be to include an "order by" clause in your query. Otherwise you're looking at sorting whatever kind of collection your call returned.

mezmo
+1  A: 

Data in a database table should be considered unordered, you can select data with a particular ordering, also, use SimpleJdbcTemplate in preference to JdbcTemplate, the same methods are available using SimpleJdbcTemplate.getJdbcOperations().

For example this code snippet will give you an ordered list of all the values in column1, assuming they are strings

final SimpleJdbcTemplate jdbcTemplate = new SimpleJdbcTemplate(datasource);
final List<String> data = jdbcTemplate.query("SELECT column1 FROM MyTable ORDER BY column1 ASC", new ParameterizedSingleColumnRowMapper<String>());
Jon Freedman
i mentioned to order db table, not to get ordered list
sergionni
As I said, data in a database table should be considered **unordered**, a database table is a set of data, not a list
Jon Freedman