我想在SpringJDBC 中实现如下sql
从sku=:sku AND make=:make 的项目中选择注释
但是当make为null属性时,查询无法找到实际存在的记录。调试后,我发现MYSQL中的"make=null"one_answers"make is null
试试这个:
public Item findBySkuAndMake(String sku, String make) {
Item item = null;
try {
String sql = "SELECT note FROM item WHERE sku = :sku AND make = :make";
SqlParameterSource parameters = new MapSqlParameterSource()
.addValue("sku", sku)
.addValue("make", make);
item = namedParameterJdbcTemplate.queryForObject(sql, parameters, new ItemRowMapper());
} catch (DataAccessExceptione) {
System.err.printf("Something went wrong while trying to search inside ITEM; this is why: %s%n", e);
}
// Then read getNote() ...or just return it (and change the method's return type)
return item;
}
// This is up to you, I don't know what's inside *Item*
private static class ItemRowMapper implements RowMapper<Item> {
@Override
public Item mapRow(ResultSet resultSet, int i) throws SQLException {
return new Item(resultSet.getString("note"), resultSet.getString("sku"),
resultSet.getString("make");
}
}
如果需要使一个(或多个)字段成为条件字段,只需在SQL查询中添加一个if
子句并将其从SqlParameterSource
中排除即可。