我有一个简单的查询,如果在方法中指定它们可以采用各种条件参数:
String sql = "SELECT * FROM TABLE WHERE userId = ?";
ArrayList<Object> dataBindings = new ArrayList<Object>();
dataBindings.add(userId);
if(startDate != null && !startDate.equalsIgnoreCase("")){
SQL += " AND datev BETWEEN ? AND ?";
dataBindings.add(startDate);
dataBindings.add(endDate);
}
if (argn > 0) {
SQL += " AND argn = ?";
dataBindings.add(argn);
}
List<SomeObject> someObjectList = this.jdbcTemplate.query(SQL, new RowMapper<SomeObject>() {
// using anonymous inner class RowMapper here
public SomeObject mapRow(ResultSet rs, int rowNum) throws SQLException {
SomeObject o = new SomeObject();
o.setId(rs.getInt("idobj"));
...
return s;
}
}, dataBindings.toArray());
但我收到错误:No operator matches the given name and argument type(s). You might need to add explicit type casts.
我必须指定每个参数的类型,但是当我将一个Objects数组传递给query()
时,它无法确定哪个参数是String或整数。
我怎么能实现这个目标?
编辑:我试过这种方式,但我觉得它可能更优雅,因为我每个条件至少检查两次因为我不知道我要通过的参数的索引而不再检查这些条件try {
InitialContext context = new InitialContext();
ComboPooledDataSource dataSource = (ComboPooledDataSource) context.lookup("jdbc/myDB");
PreparedStatement ps = dataSource.getConnection().prepareStatement(SQL);
ps.setLong(1, userId);
if(startDate != null && !startDate.equalsIgnoreCase("")) {
ps.setString(2, startDate);
ps.setString(3, endDate);
}
if (argn > 0) {
if(startDate != null && !startDate.equalsIgnoreCase("")) {
ps.setInt(3, argn);
} else {
ps.setInt(2, argn);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
我不能在这里使用RowMapper
所以我能做到:
final String finalSqlQuery = SQL;
jdbcTemplate.query(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection con)
throws SQLException {
PreparedStatement ps = con.prepareStatement(finalSqlQuery);
if(startDate != null && !startDate.equalsIgnoreCase("")) {
ps.setString(2, startDate);
ps.setString(3, endDate);
}
if (argn > 0) {
if(startDate != null && !startDate.equalsIgnoreCase("")) {
ps.setInt(3, argn);
} else {
ps.setInt(2, argn);
}
}
}
}, new RowMapper<SomeObject>() {
public SomeObject mapRow(ResultSet rs, int rowNum) throws SQLException {
SomeObject o = new SomeObject();
o.setId(rs.getInt("idobj"));
...
return s;
}
});
但通过再次检查条件来确定参数的索引对我来说似乎很难看