Java 提取预处理语句逻辑的最干净解决方案
我想将批处理和连接逻辑封装到自己的类中,如下面的代码所示,以强制正确关闭连接并使应用程序逻辑更容易Java 提取预处理语句逻辑的最干净解决方案,java,database,prepared-statement,encapsulation,Java,Database,Prepared Statement,Encapsulation,我想将批处理和连接逻辑封装到自己的类中,如下面的代码所示,以强制正确关闭连接并使应用程序逻辑更容易 public class SQLHelper { public static void insertBatched(List<String> insertStatements) { // do connection and batching logic here } } public class Application { public stat
public class SQLHelper {
public static void insertBatched(List<String> insertStatements) {
// do connection and batching logic here
}
}
public class Application {
public static void doWork() {
// create insert statements here
SQLHelper.insertBatched(statements);
}
}
公共类SQLHelper{
公共静态void insertbatch(列表insertStatements){
//在这里执行连接和批处理逻辑
}
}
公共类应用程序{
公共静态无效工作(){
//在此处创建insert语句
insertBatched(语句);
}
}
问题是将insert语句构建为字符串是一种不好的做法,应该用使用准备好的语句来代替。当使用准备好的语句时,我需要设置参数以及对同一对象进行批处理,所以在两个类之间共享它。到目前为止我想到的解决方案:
这两种解决方案都有缺点,因此我想问什么是获得最大封装的最干净的设计解决方案,同时仍然具有适当资源重新分配的安全性 如果您想手动管理SQL连接,我想您可以使用类似的方法
interface SqlWorker {
public void run(Connection c);
}
class SQLHelper {
public void execute(SqlWorker worker) throws SQLException {
Connection c = //Get the connection
try {
worker.run(c);
} finally {
c.close();
}
}
}
public static void main(String[] args) throws SQLException {
new SQLHelper().execute((c) -> {
//do any connection sql stuff here. DB helper will clean up.
});
}
使用此模式,您不必传递连接。但是做一些愚蠢的事情并使其崩溃是很容易的。此外,如果您创建一个准备好的语句或打开一个结果集,则需要显式关闭这些语句
有问题地管理连接是一种痛苦,你可能想考虑使用Spring和JPA类似的框架来管理连接/事务。
< P>如果你想手动管理SQL连接,我想你可以使用这样的东西interface SqlWorker {
public void run(Connection c);
}
class SQLHelper {
public void execute(SqlWorker worker) throws SQLException {
Connection c = //Get the connection
try {
worker.run(c);
} finally {
c.close();
}
}
}
public static void main(String[] args) throws SQLException {
new SQLHelper().execute((c) -> {
//do any connection sql stuff here. DB helper will clean up.
});
}
使用此模式,您不必传递连接。但是做一些愚蠢的事情并使其崩溃是很容易的。此外,如果您创建一个准备好的语句或打开一个结果集,则需要显式关闭这些语句
以问题的方式管理连接是一种痛苦,你可能想考虑使用Spring和JPA类似的框架来管理连接/事务。< /P>阅读连接池。这比打开和关闭连接要好得多。@Sajitshilva连接池(至少是我知道的那些)相当透明,因此池/非池版本之间的应用程序代码没有差别。使用Spring的JdbcTemplate(或重新创建它):批处理代码最好保留在应用程序部分?阅读连接池。这比打开和关闭连接要好得多。@Sajitshilva连接池(至少我知道的那些)相当透明,因此池/非池版本之间的应用程序代码没有区别。使用Spring的JdbcTemplate(或重新发明):批处理代码最好保留在应用程序部分?