任何帮助将不胜感激。我正在使用Spring JDBC进行数据访问的项目中,并且正在使用按列表示顺序的顺序执行简单查询,我目前得到的结果不一致,这意味着按顺序执行似乎不起作用。我尝试了多个数据库仍然无济于事。
String sql = "select * from account where upper(name) like upper(:query) order by name asc";
MapSqlParameterSource params = new MapSqlParameterSource().addValue("query", "%" + query + "%");
List<Account> accountsSearched = namedParameterJdbcTemplate.query(sql, params, new BeanPropertyRowMapper<Account>(Account.class));
任何想法可能是什么问题?
因此问题不在您的SQL代码内,但在搜索方法实现中存在问题”
现有代码
public List<Account> search(String uncleanedQuery, int offset) { String query = uncleanedQuery.replaceAll("([-+.^:,])",""); String sql = "select * from account where upper(name) like upper(:query) order by name asc"; MapSqlParameterSource params = new MapSqlParameterSource().addValue("query", "%" + query + "%"); List<Account> accountsSearched = namedParameterJdbcTemplate.query(sql, params, new BeanPropertyRowMapper<Account>(Account.class)); Set<Account> accountSearchSet = new HashSet<Account>(accountsSearched); List<Account> accounts = new ArrayList<Account>(accountSearchSet); return accounts; }
在上面的代码中,我们正在正确地获取数据,但是将其分配给HashSet。 HashSet不遵循名称排序,而是为Account生成随机订单,因此您每次都会获得随机订单。
解决方案1:
没有理由,您实际上需要设置。使用set只会使程序变慢。如果要获取DISTINCT数据,请修改SQL查询。public List<Account> search(String uncleanedQuery, int offset) { String query = uncleanedQuery.replaceAll("([-+.^:,])",""); String sql = "select * from account where upper(name) like upper(:query) order by name asc"; MapSqlParameterSource params = new MapSqlParameterSource().addValue("query", "%" + query + "%"); List<Account> accountsSearched = namedParameterJdbcTemplate.query(sql, params, new BeanPropertyRowMapper<Account>(Account.class)); return accountsSearched; }
解决方案2:
仍然,您想使用您的方法,然后更改代码以使用TreeSet并根据名称进行排序
public List<Account> search(String uncleanedQuery, int offset) {
String query = uncleanedQuery.replaceAll("([-+.^:,])", "");
System.out.println("Search Query Called");
String sql = "select * from account where upper(name) like upper(:query) order by name";
MapSqlParameterSource params = new MapSqlParameterSource().addValue("query", "%" + query + "%");
List<Account> accountsSearched = namedParameterJdbcTemplate.query(sql, params,
new BeanPropertyRowMapper<Account>(Account.class));
Comparator<Account> comp = new Comparator<Account>() {
@Override
public int compare(Account a1, Account a2) {
return a1.getName().compareTo(a2.getName());
}
};
SortedSet<Account> accountSearchSet = new TreeSet<Account>(comp);
accountSearchSet.addAll(accountsSearched);
List<Account> accounts = new ArrayList<Account>(accountSearchSet);
return accounts;
}