Hello. How to Sort DB records in DB table with JdbcTemplate?
What is the best solution, should execute method be used?
Hello. How to Sort DB records in DB table with JdbcTemplate?
What is the best solution, should execute method be used?
JdbcTemplate
simply executes the SQL that you provide to it in the execute
method, so use the standard SQL method: ORDER BY
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.
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>());