Scala 使用泛型的方式关闭JDBC连接

描述:

日常工作中,经常需要使用jdbc进行数据库连接,而连接资源需要进行close()关闭操作进行释放,一般都是对connection,statement,result分别进行关闭,如下所示:

private def close(connection: Connection, statement: PreparedStatement, set: ResultSet): Unit = {
    if (set != null) {
      set.close()
    }
    if (statement != null) {
      statement.close()
    }
    if (connection != null) {
      connection.close()
    }
  }

做三次if判断,从代码重复的角度考虑,能否将if判断抽取为一个方法,分别调用3次该方法以实现jdbc资源的关闭。

思路:泛型

    def closeOne[T](t: T):Unit = {
      if (t != null){
        t.close()
      }
    }

但是这会产生一个问题,就是若传入的类型T不支持close方法,则无法进行调用。因此此段代码在编译的时候便无法通过。

需要限制泛型的类型,即设置类型的上界。

查看Connection、PreparedStatement和ResultSet源码发现,均继承自AutoCloseable接口。

public interface Connection  extends Wrapper, AutoCloseable {}

public interface Statement extends Wrapper, AutoCloseable {}

public interface ResultSet extends Wrapper, AutoCloseable {}

因此设置上界为AutoCloseable。

def closeOne[T<:AutoCloseable](t: T):Unit = {
      if (t != null){
        t.close()
      }
    }

实际效果如下:

  private def close(connection: Connection, statement: PreparedStatement, set: ResultSet): Unit = {
    
    def closeOne[T<:AutoCloseable](t: T):Unit = {
      if (t != null){
        t.close()
      }
    }
    
    closeOne(set)
    closeOne(statement)
    closeOne(connection)
    }

重构:利用可变参数进行map操作

以上已经实现了功能,为整体代码的整洁对其进行重构,如下:

  def closed[T <: AutoCloseable](args: T*): Unit = {
    args.foreach(each => {
      if (each != null) {
        each.close()
      }
    })
  }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值