【问题标题】:JDBI bind value or null in query?查询中的 JDBI 绑定值或空值?
【发布时间】:2021-05-27 07:05:02
【问题描述】:

JDBI 查询需要支持为查询中的多个列设置一个值或 null。

但是,下面是插入空字符串,而不是空值:

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();

【问题讨论】:

    标签: java mysql sql jdbc jdbi


    【解决方案1】:

    编写需要直接访问JDBCprepared statement的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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-10
      • 1970-01-01
      • 2022-11-30
      • 2018-07-20
      • 2010-11-12
      • 2016-01-09
      • 2017-02-21
      相关资源
      最近更新 更多