JDBI 查询需要支持为查询中的多个列设置一个值或空值。
但是,下面插入的是空字符串和零,而不是空值:
handle
.createUpdate("REPLACE INTO products(id, name, price) VALUES (:id, :name, :price)")
.bind("id", product.getId())
.bind("name", product.getName())
.bind("price", product.getPrice())
.execute();
此外,当我从同一数据库中SELECT
记录并使用以下行映射器时,结果为零(对于 Double,尽管 String 似乎映射为 null OK):
return Product.newBuilder()
.setId(rs.getString("id"))
.setName(rs.getString("name"))
.setPrice(rs.getDouble("price"))
.build();
最佳答案
为了写,需要直接访问JDBC准备语句的setNull方法:
var stmt = handle
.createUpdate("REPLACE INTO products(id, name, price) VALUES (:id, :name, :price)")
.bind("id", deal.getId());
bindValueOrNull(stmt, "name", product.getName());
bindValueOrNull(stmt, "price", product.getPrice());
stmt.execute();
/**
Bind a non-null value to the named query parameter, or else SQL Types.NULL value
@param stmt being prepared
@param key to bind
@param value or null
*/
private void bindValueOrNull(Update stmt, String key, @Nullable Object value) {
if (Objects.nonNull(value))
stmt.bind(key, value);
else
stmt.bindNull(key, Types.NULL);
}
对于读取,有必要使用 getObject
方法进行空检查:
return Product.newBuilder()
.setId(rs.getString("id"))
.setName(rs.getString("name"))
.setPrice(getDoubleOrNull(rs, "price"))
.build();
/**
Get Double value, or null, from a result set
@param rs result set
@param key of column
@return Double or null
*/
@Nullable
private static Double getDoubleOrNull(ResultSet rs, String key) throws SQLException {
return Objects.nonNull(rs.getObject(key)) ? rs.getDouble(key) : null;
}
关于java - 查询中的 JDBI 绑定(bind)值或空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66359744/