How to manage DSLContext in jooq? (close connection)

前端 未结 1 878
庸人自扰
庸人自扰 2021-02-08 23:58

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 = MySQLCo         


        
相关标签:
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

    0 讨论(0)
提交回复
热议问题