forked from plusone/simple-jdbc
refactor: JdbcOperationSupport 中无参数 SQL 改用 Statement 执行
update、updateAndReturnKeys、queryInternal 三个方法根据是否有参数,分别走 PreparedStatement(有参数)或 Statement(无参数),避免无参数时不必要的预编译开销
This commit is contained in:
@@ -37,6 +37,8 @@ import java.util.List;
|
||||
import javax.annotation.Nonnull;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
import xyz.zhouxy.plusone.commons.util.ArrayTools;
|
||||
|
||||
/**
|
||||
* JdbcOperationSupport
|
||||
*
|
||||
@@ -160,11 +162,18 @@ class JdbcOperationSupport {
|
||||
throws SQLException {
|
||||
assertConnectionNotNull(conn);
|
||||
assertSqlNotNull(sql);
|
||||
if (ArrayTools.isNotEmpty(params)) {
|
||||
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
|
||||
fillStatement(stmt, params);
|
||||
return stmt.executeUpdate();
|
||||
}
|
||||
}
|
||||
else {
|
||||
try (Statement stmt = conn.createStatement()) {
|
||||
return stmt.executeUpdate(sql);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行 SQL 并返回生成的 keys
|
||||
@@ -182,6 +191,7 @@ class JdbcOperationSupport {
|
||||
assertConnectionNotNull(conn);
|
||||
assertSqlNotNull(sql);
|
||||
assertRowMapperNotNull(rowMapper);
|
||||
if (ArrayTools.isNotEmpty(params)) {
|
||||
try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
|
||||
fillStatement(stmt, params);
|
||||
stmt.executeUpdate();
|
||||
@@ -191,6 +201,16 @@ class JdbcOperationSupport {
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
try (Statement stmt = conn.createStatement()) {
|
||||
stmt.executeUpdate(sql);
|
||||
try (ResultSet generatedKeys = stmt.getGeneratedKeys()) {
|
||||
final ResultHandler<List<T>> resultHandler = ResultHandler.mapToList(rowMapper);
|
||||
return resultHandler.handle(generatedKeys);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量更新
|
||||
@@ -288,11 +308,19 @@ class JdbcOperationSupport {
|
||||
@Nullable Object[] params,
|
||||
@Nonnull ResultHandler<T> resultHandler)
|
||||
throws SQLException {
|
||||
if (ArrayTools.isNotEmpty(params)) {
|
||||
try (PreparedStatement stmt = createPreparedStatementInternal(conn, sql, params);
|
||||
ResultSet rs = stmt.executeQuery()) {
|
||||
return resultHandler.handle(rs);
|
||||
}
|
||||
}
|
||||
else {
|
||||
try (Statement stmt = conn.createStatement();
|
||||
ResultSet rs = stmt.executeQuery(sql)) {
|
||||
return resultHandler.handle(rs);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static PreparedStatement createPreparedStatementInternal(
|
||||
@Nonnull Connection conn,
|
||||
|
||||
Reference in New Issue
Block a user