How to manage DSLContext in jooq? (close connection)

给你一囗甜甜゛ 提交于 2019-12-04 21:35:09

问题


This is how I implement each jooq query that i want.

UtilClass{

 //one per table more or less
 static void methodA(){

  //my method
  Connection con = MySQLConnection.getConexion(); //open
  DSLContext create = DSL.using(con, SQLDialect.MYSQL); //open

  /* my logic and jooq querys */ //The code !!!!!!!

  try {

    if ( con != null )
       con.close(); //close
  } catch (SQLException e) {

  } //close

  con=null; //close
  create=null; //close
 }
}

Am I overworking here? / Is it safe to leave the Context and Connection Open?

In case it is safe to leave it open I would rather work with 1 static field DSLContext per UtilClass (and only the commented section would be on my methods). I would be opening a connection for each UtilClass since I am encapsulating the methods per table (more or less).


回答1:


DSLContext is usually not a resource, so you can leave it "open", i.e. you can let the garbage collector collect it for you.

A JDBC Connection, however, is a resource, and as all resources, you should always close it explicitly. The correct way to close resources in Java 7+ is by using the try-with-resources statement:

static void methodA() {
    try (Connection con = MySQLConnection.getConexion()) {
        DSLContext ctx = DSL.using(con, SQLDialect.MYSQL); //open

        /* my logic and jooq queries */

        // "ctx" goes out of scope here, and can be garbage-collected
    }   // "con" will be closed here by the try-with-resources statement
 }

More information about the try-with-resources statement can be seen here. Please also notice that the jOOQ tutorial uses the try-with-resources statement when using standalone JDBC connections.

When is DSLContext a resource?

An exception to the above is when you let your DSLContext instance manage the Connection itself, e.g. by passing a connection URL as follows:

try (DSLContext ctx = DSL.using("jdbc:url:something", "username", "password")) {
}

In this case, you will need to close() the DSLContext as shown above



来源:https://stackoverflow.com/questions/27773698/how-to-manage-dslcontext-in-jooq-close-connection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!