我有一个简单的查询,如果在方法中指定了各种条件参数,它可以采用:
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.
我必须指定每个参数的类型,但是当我将对象数组传递给 时query()
,它无法确定哪个参数是字符串或整数。
我怎么能做到这一点?
编辑:我尝试过这种方式,但我认为它可能更优雅,因为我每个条件至少检查两次,因为如果不再次检查这些条件,我将无法知道要传递的参数的索引
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;
}
});
但是通过再次检查条件来确定参数的索引对我来说似乎真的很难看