问题描述
这是我实现所需的每个jooq查询的方式.
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?
如果可以安全地将其保持打开状态,那么我宁愿每个UtilClass
使用1个静态字段DSLContext(并且只有注释的部分在我的方法中).因为要封装每个表中的方法(或多或少),所以我将为每个UtilClass打开一个连接.
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).
推荐答案
DSLContext
通常不是资源,因此您可以将其保持打开"状态,即可以让垃圾收集器为您收集它.
DSLContext
is usually not a resource, so you can leave it "open", i.e. you can let the garbage collector collect it for you.
但是,JDBC Connection
是一种资源,作为所有资源,您应该始终显式关闭它.在Java 7+中,关闭资源的正确方法是使用try-with-resources语句:
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
}
有关try-with-resources语句的更多信息,请参见此处.另请注意, jOOQ教程在使用独立的JDBC连接时使用try-with-resources语句.
上述情况的例外是,当您让您的DSLContext
实例管理Connection
本身时,例如通过传递如下的连接URL:
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")) {
}
在这种情况下,您将需要如上图所示close()
DSLContext
In this case, you will need to close()
the DSLContext
as shown above
这篇关于如何在jooq中管理DSLContext? (紧密连接)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!