Question

How to Sort DB records in DB table with JdbcTemplate?

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

Was it helpful?

Solution

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

OTHER TIPS

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>());

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top