我以这种方式使用 Spring Jdbc 模板:
public List<User> getUsersForGrid(int rows, int page, String sidx,
String sord) {
int fromRecord = 0;
int toRecord = 0;
toRecord = page * rows;
fromRecord = (page - 1) * rows;
StringBuilder sqlB = new StringBuilder();
sqlB.append("SELECT user_id, username ");
sqlB.append("FROM users ");
sqlB.append("WHERE :fromRecord <= rownum AND rownum <= :toRecord ");
sqlB.append("ORDER BY %s %s ");
String sql = String.format(sqlB.toString(), sidx, sord);
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue("fromRecord", fromRecord);
params.addValue("toRecord", toRecord);
List<Map<String, Object>> rsRows = this.jdbcTemplate.queryForList(sql
.toString(),params);
List<User> users = new ArrayList<User>();
for (Map<String, Object> row : rsRows) {
BigDecimal id = (BigDecimal) row.get("user_id");
String username = (String) row.get("username");
User user = new User(id.intValue(), username);
users.add(user);
}
return users;
}
并得到 java.sql.SQLException: Invalid column type
sidx 是 nate 列(例如“user_id”) sord 是 asc/desc
不传递参数时(只执行
sql.append("SELECT user_id, username ");
sql.append("FROM users ");
) 一切都好。
更新:适用于:
sqlB.append("WHERE ? <= rownum AND rownum <= ? ");
和
this.jdbcTemplate.queryForList(sql.toString(),new Object[]{fromRecord, toRecord});
似乎是 Spring MapSqlParameterSource 和命名参数的问题。我使用 Spring 3.1.3
数据库是 Oracle 11.2
describe users;
Name Null Type
------------------------------ -------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
USER_ID NOT NULL NUMBER
USERNAME NOT NULL VARCHAR2(40)
PASSWORD NOT NULL VARCHAR2(20)
ENABLED NOT NULL NUMBER