Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance. Project price only 1 $
You can buy this project and download/modify it how often you want.
/*
* Copyright (c) 2015, Haiyang Li.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.landawn.abacus.jdbc;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import com.landawn.abacus.annotation.Beta;
import com.landawn.abacus.annotation.Internal;
import com.landawn.abacus.cache.Cache;
import com.landawn.abacus.exception.UncheckedSQLException;
import com.landawn.abacus.jdbc.Jdbc.BiParametersSetter;
import com.landawn.abacus.jdbc.Jdbc.BiResultExtractor;
import com.landawn.abacus.jdbc.Jdbc.BiRowFilter;
import com.landawn.abacus.jdbc.Jdbc.BiRowMapper;
import com.landawn.abacus.jdbc.Jdbc.OutParam;
import com.landawn.abacus.jdbc.Jdbc.OutParamResult;
import com.landawn.abacus.jdbc.Jdbc.ResultExtractor;
import com.landawn.abacus.jdbc.Jdbc.RowExtractor;
import com.landawn.abacus.jdbc.Jdbc.RowFilter;
import com.landawn.abacus.jdbc.Jdbc.RowMapper;
import com.landawn.abacus.jdbc.SQLTransaction.CreatedBy;
import com.landawn.abacus.jdbc.dao.CrudDao;
import com.landawn.abacus.jdbc.dao.Dao;
import com.landawn.abacus.logging.Logger;
import com.landawn.abacus.logging.LoggerFactory;
import com.landawn.abacus.parser.ParserUtil;
import com.landawn.abacus.parser.ParserUtil.BeanInfo;
import com.landawn.abacus.parser.ParserUtil.PropInfo;
import com.landawn.abacus.type.Type;
import com.landawn.abacus.util.AsyncExecutor;
import com.landawn.abacus.util.Charsets;
import com.landawn.abacus.util.CheckedStream;
import com.landawn.abacus.util.ClassUtil;
import com.landawn.abacus.util.ContinuableFuture;
import com.landawn.abacus.util.DataSet;
import com.landawn.abacus.util.EntityId;
import com.landawn.abacus.util.Fn;
import com.landawn.abacus.util.Fn.BiConsumers;
import com.landawn.abacus.util.Holder;
import com.landawn.abacus.util.IOUtil;
import com.landawn.abacus.util.ImmutableMap;
import com.landawn.abacus.util.InternalUtil;
import com.landawn.abacus.util.N;
import com.landawn.abacus.util.NamingPolicy;
import com.landawn.abacus.util.ObjectPool;
import com.landawn.abacus.util.ParsedSql;
import com.landawn.abacus.util.QueryUtil;
import com.landawn.abacus.util.RowDataSet;
import com.landawn.abacus.util.SQLBuilder;
import com.landawn.abacus.util.SQLBuilder.SP;
import com.landawn.abacus.util.SQLMapper;
import com.landawn.abacus.util.SQLOperation;
import com.landawn.abacus.util.Seid;
import com.landawn.abacus.util.Splitter;
import com.landawn.abacus.util.Strings;
import com.landawn.abacus.util.Throwables;
import com.landawn.abacus.util.Tuple;
import com.landawn.abacus.util.Tuple.Tuple2;
import com.landawn.abacus.util.Tuple.Tuple3;
import com.landawn.abacus.util.u.Optional;
import com.landawn.abacus.util.function.TriConsumer;
import com.landawn.abacus.util.stream.EntryStream;
import com.landawn.abacus.util.stream.Stream;
import com.landawn.abacus.util.stream.Stream.StreamEx;
/**
*
* Performance Tips:
*
Avoid unnecessary/repeated database calls.
*
Only fetch the columns you need or update the columns you want.
*
Index is the key point in a lot of database performance issues.
*
*
*
* @see {@link com.landawn.abacus.condition .ConditionFactory}
* @see {@link com.landawn.abacus.condition.ConditionFactory.CF}
* @see {@link com.landawn.abacus.annotation.ReadOnly}
* @see {@link com.landawn.abacus.annotation.ReadOnlyId}
* @see {@link com.landawn.abacus.annotation.NonUpdatable}
* @see {@link com.landawn.abacus.annotation.Transient}
* @see {@link com.landawn.abacus.annotation.Table}
* @see {@link com.landawn.abacus.annotation.Column}
* @see http://docs.oracle.com/javase/8/docs/api/java/sql/Connection.html
* @see http://docs.oracle.com/javase/8/docs/api/java/sql/Statement.html
* @see http://docs.oracle.com/javase/8/docs/api/java/sql/PreparedStatement.html
* @see http://docs.oracle.com/javase/8/docs/api/java/sql/ResultSet.html
* @since 0.8
* @author Haiyang Li
*/
@SuppressWarnings({ "java:S1192", "java:S6539" })
public final class JdbcUtil {
static final Logger logger = LoggerFactory.getLogger(JdbcUtil.class);
static final Logger sqlLogger = LoggerFactory.getLogger("com.landawn.abacus.SQL");
static final char CHAR_ZERO = 0;
public static final int DEFAULT_BATCH_SIZE = 200;
// static final int MAX_BATCH_SIZE = 1000;
public static final int DEFAULT_FETCH_SIZE_FOR_BIG_RESULT = 1000;
public static final int DEFAULT_FETCH_SIZE_FOR_STREAM = 100;
public static final Throwables.Function DEFAULT_SQL_EXTRACTOR = stmt -> {
Statement stmtToUse = stmt;
String clsName = stmtToUse.getClass().getName();
if ((clsName.startsWith("com.zaxxer.hikari") || clsName.startsWith("com.mchange.v2.c3p0")) && stmt.isWrapperFor(Statement.class)) {
stmtToUse = stmt.unwrap(Statement.class);
clsName = stmtToUse.getClass().getName();
}
if (clsName.startsWith("oracle.jdbc")) {
if (stmtToUse instanceof oracle.jdbc.internal.OraclePreparedStatement) { //NOSONAR
try {
return ((oracle.jdbc.internal.OraclePreparedStatement) stmtToUse).getOriginalSql();
} catch (SQLException e) {
// ignore.
}
}
}
return stmtToUse.toString();
};
static Throwables.Function _sqlExtractor = DEFAULT_SQL_EXTRACTOR; //NOSONAR
// TODO is it right to do it?
// static final KeyedObjectPool> stmtPoolForSql = PoolFactory.createKeyedObjectPool(1000, 3000);
// ...
static final String CURRENT_DIR_PATH = "./";
static final AsyncExecutor asyncExecutor = new AsyncExecutor(//
N.max(64, IOUtil.CPU_CORES * 8), // coreThreadPoolSize
N.max(128, IOUtil.CPU_CORES * 16), // maxThreadPoolSize
180L, TimeUnit.SECONDS);
static final BiParametersSetter super PreparedQuery, ? super Object[]> DEFAULT_STMT_SETTER = (stmt, parameters) -> {
for (int i = 0, len = parameters.length; i < len; i++) {
stmt.setObject(i + 1, parameters[i]);
}
};
private static final Set sqlStateForTableNotExists = N.newHashSet();
static {
sqlStateForTableNotExists.add("42S02"); // for MySQCF.
sqlStateForTableNotExists.add("42P01"); // for PostgreSQCF.
sqlStateForTableNotExists.add("42501"); // for HSQLDB.
}
private JdbcUtil() {
// singleton
}
/**
*
*
* @param ds
* @return
* @throws UncheckedSQLException
*/
public static DBProductInfo getDBProductInfo(final javax.sql.DataSource ds) throws UncheckedSQLException {
Connection conn = null;
try {
conn = ds.getConnection();
return getDBProductInfo(conn);
} catch (SQLException e) {
throw new UncheckedSQLException(e);
} finally {
JdbcUtil.releaseConnection(conn, ds);
}
}
/**
*
*
* @param conn
* @return
* @throws UncheckedSQLException
*/
public static DBProductInfo getDBProductInfo(final Connection conn) throws UncheckedSQLException {
try {
final DatabaseMetaData metaData = conn.getMetaData();
final String dbProudctName = metaData.getDatabaseProductName();
final String dbProudctVersion = metaData.getDatabaseProductVersion();
final String upperCaseProductName = dbProudctName.toUpperCase();
DBVersion dbVersion = DBVersion.OTHERS;
if (upperCaseProductName.contains("H2")) {
dbVersion = DBVersion.H2;
} else if (upperCaseProductName.contains("HSQL")) {
dbVersion = DBVersion.HSQLDB;
} else if (upperCaseProductName.contains("MYSQL")) {
if (dbProudctVersion.startsWith("5.5")) {
dbVersion = DBVersion.MYSQL_5_5;
} else if (dbProudctVersion.startsWith("5.6")) {
dbVersion = DBVersion.MYSQL_5_6;
} else if (dbProudctVersion.startsWith("5.7")) {
dbVersion = DBVersion.MYSQL_5_7;
} else if (dbProudctVersion.startsWith("5.8")) {
dbVersion = DBVersion.MYSQL_5_8;
} else if (dbProudctVersion.startsWith("5.9")) {
dbVersion = DBVersion.MYSQL_5_9;
} else if (dbProudctVersion.startsWith("6")) {
dbVersion = DBVersion.MYSQL_6;
} else if (dbProudctVersion.startsWith("7")) {
dbVersion = DBVersion.MYSQL_7;
} else if (dbProudctVersion.startsWith("8")) {
dbVersion = DBVersion.MYSQL_8;
} else if (dbProudctVersion.startsWith("9")) {
dbVersion = DBVersion.MYSQL_9;
} else if (dbProudctVersion.startsWith("10")) {
dbVersion = DBVersion.MYSQL_10;
} else {
dbVersion = DBVersion.MYSQL_OTHERS;
}
} else if (upperCaseProductName.contains("POSTGRESQL")) {
if (dbProudctVersion.startsWith("9.2")) {
dbVersion = DBVersion.POSTGRESQL_9_2;
} else if (dbProudctVersion.startsWith("9.3")) {
dbVersion = DBVersion.POSTGRESQL_9_3;
} else if (dbProudctVersion.startsWith("9.4")) {
dbVersion = DBVersion.POSTGRESQL_9_4;
} else if (dbProudctVersion.startsWith("9.5")) {
dbVersion = DBVersion.POSTGRESQL_9_5;
} else if (dbProudctVersion.startsWith("10")) {
dbVersion = DBVersion.POSTGRESQL_10;
} else if (dbProudctVersion.startsWith("11")) {
dbVersion = DBVersion.POSTGRESQL_11;
} else if (dbProudctVersion.startsWith("12")) {
dbVersion = DBVersion.POSTGRESQL_12;
} else {
dbVersion = DBVersion.POSTGRESQL_OTHERS;
}
} else if (upperCaseProductName.contains("ORACLE")) {
dbVersion = DBVersion.ORACLE;
} else if (upperCaseProductName.contains("DB2")) {
dbVersion = DBVersion.DB2;
} else if (upperCaseProductName.contains("SQL SERVER")) {
dbVersion = DBVersion.SQL_SERVER;
}
return new DBProductInfo(dbProudctName, dbProudctName, dbVersion);
} catch (SQLException e) {
throw new UncheckedSQLException(e);
}
}
/**
* Creates the DataSource.
*
* @param url
* @param user
* @param password
* @return
*/
public static javax.sql.DataSource createHikariDataSource(final String url, final String user, final String password) {
try {
final com.zaxxer.hikari.HikariConfig config = new com.zaxxer.hikari.HikariConfig();
config.setJdbcUrl(url);
config.setUsername(user);
config.setPassword(password);
return new com.zaxxer.hikari.HikariDataSource(config);
} catch (Exception e) {
throw N.toRuntimeException(e);
}
}
/**
* Creates the DataSource.
*
* @param url
* @param user
* @param password
* @return
*/
public static javax.sql.DataSource createC3p0DataSource(final String url, final String user, final String password) {
try {
final com.mchange.v2.c3p0.ComboPooledDataSource cpds = new com.mchange.v2.c3p0.ComboPooledDataSource();
cpds.setJdbcUrl(url);
cpds.setUser(user);
cpds.setPassword(password);
return cpds;
} catch (Exception e) {
throw N.toRuntimeException(e);
}
}
/**
* Creates the connection.
*
* @param url
* @param user
* @param password
* @return
* @throws UncheckedSQLException the unchecked SQL exception
*/
public static Connection createConnection(final String url, final String user, final String password) throws UncheckedSQLException {
return createConnection(getDriverClasssByUrl(url), url, user, password);
}
/**
* Creates the connection.
*
* @param driverClass
* @param url
* @param user
* @param password
* @return
* @throws UncheckedSQLException the unchecked SQL exception
*/
public static Connection createConnection(final String driverClass, final String url, final String user, final String password)
throws UncheckedSQLException {
final Class extends Driver> cls = ClassUtil.forClass(driverClass);
return createConnection(cls, url, user, password);
}
/**
* Creates the connection.
*
* @param driverClass
* @param url
* @param user
* @param password
* @return
* @throws UncheckedSQLException the unchecked SQL exception
*/
public static Connection createConnection(final Class extends Driver> driverClass, final String url, final String user, final String password)
throws UncheckedSQLException {
try {
DriverManager.registerDriver(N.newInstance(driverClass));
return DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
throw new UncheckedSQLException("Failed to close create connection", e);
}
}
/**
* Gets the driver classs by url.
*
* @param url
* @return
*/
private static Class extends Driver> getDriverClasssByUrl(final String url) {
N.checkArgNotEmpty(url, "url");
Class extends Driver> driverClass = null;
// jdbc:mysql://localhost:3306/abacustest
if (Strings.indexOfIgnoreCase(url, "mysql") >= 0) {
driverClass = ClassUtil.forClass("com.mysql.Driver");
// jdbc:postgresql://localhost:5432/abacustest
} else if (Strings.indexOfIgnoreCase(url, "postgresql") >= 0) {
driverClass = ClassUtil.forClass("org.postgresql.Driver");
// jdbc:h2:hsql://:/
} else if (Strings.indexOfIgnoreCase(url, "h2") >= 0) {
driverClass = ClassUtil.forClass("org.h2.Driver");
// jdbc:hsqldb:hsql://localhost/abacustest
} else if (Strings.indexOfIgnoreCase(url, "hsqldb") >= 0) {
driverClass = ClassUtil.forClass("org.hsqldb.JDBCDriver");
// url=jdbc:oracle:thin:@localhost:1521:abacustest
} else if (Strings.indexOfIgnoreCase(url, "oracle") >= 0) {
driverClass = ClassUtil.forClass("oracle.driver.OracleDriver");
// url=jdbc:sqlserver://localhost:1433;Database=abacustest
} else if (Strings.indexOfIgnoreCase(url, "sqlserver") >= 0) {
driverClass = ClassUtil.forClass("com.microsoft.sqlserver.SQLServerDriver");
// jdbc:db2://localhost:50000/abacustest
} else if (Strings.indexOfIgnoreCase(url, "db2") >= 0) {
driverClass = ClassUtil.forClass("com.ibm.db2.jcc.DB2Driver");
} else {
throw new IllegalArgumentException(
"Can not identity the driver class by url: " + url + ". Only mysql, postgresql, hsqldb, sqlserver, oracle and db2 are supported currently");
}
return driverClass;
}
private static boolean isInSpring = true;
static {
try {
isInSpring = ClassUtil.forClass("org.springframework.datasource.DataSourceUtils") != null;
} catch (Throwable e) {
isInSpring = false;
}
}
/**
* Spring Transaction is supported and Integrated.
* If this method is called where a Spring transaction is started with the specified {@code DataSource},
* the {@code Connection} started the Spring Transaction will be returned. Otherwise a {@code Connection} directly from the specified {@code DataSource}(Connection pool) will be returned.
*
* @param ds
* @return
* @throws UncheckedSQLException the unchecked SQL exception
*/
public static Connection getConnection(final javax.sql.DataSource ds) throws UncheckedSQLException {
if (isInSpring && !isSpringTransactionalDisabled_TL.get()) { //NOSONAR
try {
return org.springframework.jdbc.datasource.DataSourceUtils.getConnection(ds);
} catch (NoClassDefFoundError e) {
isInSpring = false;
try {
return ds.getConnection();
} catch (SQLException e1) {
throw new UncheckedSQLException(e1);
}
}
} else {
try {
return ds.getConnection();
} catch (SQLException e) {
throw new UncheckedSQLException(e);
}
}
}
/**
* Spring Transaction is supported and Integrated.
* If this method is called where a Spring transaction is started with the specified {@code DataSource},
* the specified {@code Connection} won't be returned to {@code DataSource}(Connection pool) until the transaction is committed or rolled back. Otherwise the specified {@code Connection} will be directly returned back to {@code DataSource}(Connection pool).
*
* @param conn
* @param ds
*/
public static void releaseConnection(final Connection conn, final javax.sql.DataSource ds) {
if (conn == null) {
return;
}
if (isInSpring && ds != null && !isSpringTransactionalDisabled_TL.get()) { //NOSONAR
try {
org.springframework.jdbc.datasource.DataSourceUtils.releaseConnection(conn, ds);
} catch (NoClassDefFoundError e) {
isInSpring = false;
JdbcUtil.closeQuietly(conn);
}
} else {
JdbcUtil.closeQuietly(conn);
}
}
/**
* Creates the close handler.
*
* @param conn
* @param ds
* @return
*/
static Runnable createCloseHandler(final Connection conn, final javax.sql.DataSource ds) {
return () -> releaseConnection(conn, ds);
}
/**
*
* @param rs
* @throws UncheckedSQLException the unchecked SQL exception
*/
public static void close(final ResultSet rs) throws UncheckedSQLException {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
throw new UncheckedSQLException(e);
}
}
}
/**
*
* @param rs
* @param closeStatement
* @throws UncheckedSQLException the unchecked SQL exception
*/
public static void close(final ResultSet rs, final boolean closeStatement) throws UncheckedSQLException {
close(rs, closeStatement, false);
}
/**
*
* @param rs
* @param closeStatement
* @param closeConnection
* @throws IllegalArgumentException if {@code closeStatement = false} while {@code closeConnection = true}.
* @throws UncheckedSQLException the unchecked SQL exception
*/
public static void close(final ResultSet rs, final boolean closeStatement, final boolean closeConnection)
throws IllegalArgumentException, UncheckedSQLException {
if (closeConnection && !closeStatement) {
throw new IllegalArgumentException("'closeStatement' can't be false while 'closeConnection' is true");
}
if (rs == null) {
return;
}
Connection conn = null;
Statement stmt = null;
try {
if (closeStatement) {
stmt = rs.getStatement();
}
if (closeConnection && stmt != null) {
conn = stmt.getConnection();
}
} catch (SQLException e) {
throw new UncheckedSQLException(e);
} finally {
close(rs, stmt, conn);
}
}
/**
*
* @param stmt
* @throws UncheckedSQLException the unchecked SQL exception
*/
public static void close(final Statement stmt) throws UncheckedSQLException {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
throw new UncheckedSQLException(e);
}
}
}
/**
*
* @param conn
* @throws UncheckedSQLException the unchecked SQL exception
* @deprecated consider using {@link #releaseConnection(Connection, javax.sql.DataSource)}
*/
@Deprecated
public static void close(final Connection conn) throws UncheckedSQLException {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
throw new UncheckedSQLException(e);
}
}
}
/**
*
* @param rs
* @param stmt
* @throws UncheckedSQLException the unchecked SQL exception
*/
public static void close(final ResultSet rs, final Statement stmt) throws UncheckedSQLException {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
throw new UncheckedSQLException(e);
} finally {
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException e) {
throw new UncheckedSQLException(e); //NOSONAR
}
}
}
/**
*
* @param stmt
* @param conn
* @throws UncheckedSQLException the unchecked SQL exception
*/
public static void close(final Statement stmt, final Connection conn) throws UncheckedSQLException {
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException e) {
throw new UncheckedSQLException(e);
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
throw new UncheckedSQLException(e); //NOSONAR
}
}
}
/**
*
* @param rs
* @param stmt
* @param conn
* @throws UncheckedSQLException the unchecked SQL exception
*/
public static void close(final ResultSet rs, final Statement stmt, final Connection conn) throws UncheckedSQLException {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
throw new UncheckedSQLException(e);
} finally {
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException e) {
throw new UncheckedSQLException(e); //NOSONAR
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
throw new UncheckedSQLException(e); //NOSONAR
}
}
}
}
/**
* Unconditionally close an ResultSet.
*
* Equivalent to {@link ResultSet#close()}, except any exceptions will be ignored.
* This is typically used in finally blocks.
*
* @param rs
*/
public static void closeQuietly(final ResultSet rs) {
closeQuietly(rs, null, null);
}
/**
*
* @param rs
* @param closeStatement
* @throws UncheckedSQLException the unchecked SQL exception
*/
public static void closeQuietly(final ResultSet rs, final boolean closeStatement) throws UncheckedSQLException {
closeQuietly(rs, closeStatement, false);
}
/**
*
* @param rs
* @param closeStatement
* @param closeConnection
* @throws IllegalArgumentException if {@code closeStatement = false} while {@code closeConnection = true}.
*/
public static void closeQuietly(final ResultSet rs, final boolean closeStatement, final boolean closeConnection) throws IllegalArgumentException {
if (closeConnection && !closeStatement) {
throw new IllegalArgumentException("'closeStatement' can't be false while 'closeConnection' is true");
}
if (rs == null) {
return;
}
Connection conn = null;
Statement stmt = null;
try {
if (closeStatement) {
stmt = rs.getStatement();
}
if (closeConnection && stmt != null) {
conn = stmt.getConnection();
}
} catch (SQLException e) {
logger.error("Failed to get Statement or Connection by ResultSet", e);
} finally {
closeQuietly(rs, stmt, conn);
}
}
/**
* Unconditionally close an Statement.
*
* Equivalent to {@link Statement#close()}, except any exceptions will be ignored.
* This is typically used in finally blocks.
*
* @param stmt
*/
public static void closeQuietly(final Statement stmt) {
closeQuietly(null, stmt, null);
}
/**
* Unconditionally close an Connection.
*
* Equivalent to {@link Connection#close()}, except any exceptions will be ignored.
* This is typically used in finally blocks.
*
* @param conn
* @deprecated consider using {@link #releaseConnection(Connection, javax.sql.DataSource)}
*/
@Deprecated
public static void closeQuietly(final Connection conn) {
closeQuietly(null, null, conn);
}
/**
* Unconditionally close the ResultSet, Statement.
*
* Equivalent to {@link ResultSet#close()}, {@link Statement#close()}, except any exceptions will be ignored.
* This is typically used in finally blocks.
*
* @param rs
* @param stmt
*/
public static void closeQuietly(final ResultSet rs, final Statement stmt) {
closeQuietly(rs, stmt, null);
}
/**
* Unconditionally close the Statement, Connection.
*
* Equivalent to {@link Statement#close()}, {@link Connection#close()}, except any exceptions will be ignored.
* This is typically used in finally blocks.
*
* @param stmt
* @param conn
*/
public static void closeQuietly(final Statement stmt, final Connection conn) {
closeQuietly(null, stmt, conn);
}
/**
* Unconditionally close the ResultSet, Statement, Connection.
*
* Equivalent to {@link ResultSet#close()}, {@link Statement#close()}, {@link Connection#close()}, except any exceptions will be ignored.
* This is typically used in finally blocks.
*
* @param rs
* @param stmt
* @param conn
*/
public static void closeQuietly(final ResultSet rs, final Statement stmt, final Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (Exception e) {
logger.error("Failed to close ResultSet", e);
}
}
if (stmt != null) {
try {
stmt.close();
} catch (Exception e) {
logger.error("Failed to close Statement", e);
}
}
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
logger.error("Failed to close Connection", e);
}
}
}
/**
*
* @param rs
* @param n the count of row to move ahead.
* @return
* @throws SQLException
*/
public static int skip(final ResultSet rs, int n) throws SQLException {
return skip(rs, (long) n);
}
private static final Set> resultSetClassNotSupportAbsolute = ConcurrentHashMap.newKeySet();
/**
*
* @param rs
* @param n the count of row to move ahead.
* @return
* @throws SQLException
* @see {@link ResultSet#absolute(int)}
*/
public static int skip(final ResultSet rs, long n) throws SQLException {
if (n <= 0) {
return 0;
} else if (n == 1) {
return rs.next() ? 1 : 0;
} else {
final int currentRow = rs.getRow();
if (n <= Integer.MAX_VALUE) {
if (n > Integer.MAX_VALUE - currentRow
|| (resultSetClassNotSupportAbsolute.size() > 0 && resultSetClassNotSupportAbsolute.contains(rs.getClass()))) {
while (n-- > 0L && rs.next()) {
// continue.
}
} else {
try {
rs.absolute((int) n + currentRow);
} catch (SQLException e) {
while (n-- > 0L && rs.next()) {
// continue.
}
resultSetClassNotSupportAbsolute.add(rs.getClass());
}
}
} else {
while (n-- > 0L && rs.next()) {
// continue.
}
}
return rs.getRow() - currentRow;
}
}
/**
* Gets the column count.
*
* @param rs
* @return
* @throws SQLException
*/
public static int getColumnCount(ResultSet rs) throws SQLException {
return rs.getMetaData().getColumnCount();
}
/**
* Gets the column name list.
*
* @param conn
* @param tableName
* @return
* @throws SQLException
*/
public static List getColumnNameList(final Connection conn, final String tableName) throws SQLException {
final String query = "SELECT * FROM " + tableName + " WHERE 1 > 2";
PreparedStatement stmt = null;
ResultSet rs = null;
try {
stmt = prepareStatement(conn, query);
rs = executeQuery(stmt);
final ResultSetMetaData metaData = rs.getMetaData();
final int columnCount = metaData.getColumnCount();
final List columnNameList = new ArrayList<>(columnCount);
for (int i = 1, n = columnCount + 1; i < n; i++) {
columnNameList.add(metaData.getColumnName(i));
}
return columnNameList;
} finally {
closeQuietly(rs, stmt);
}
}
/**
*
*
* @param rs
* @return
* @throws SQLException
*/
public static List getColumnLabelList(ResultSet rs) throws SQLException {
final ResultSetMetaData metaData = rs.getMetaData();
final int columnCount = metaData.getColumnCount();
final List labelList = new ArrayList<>(columnCount);
for (int i = 1, n = columnCount + 1; i < n; i++) {
labelList.add(getColumnLabel(metaData, i));
}
return labelList;
}
/**
* Gets the column label.
*
* @param rsmd
* @param columnIndex
* @return
* @throws SQLException
*/
public static String getColumnLabel(final ResultSetMetaData rsmd, final int columnIndex) throws SQLException {
final String result = rsmd.getColumnLabel(columnIndex);
return Strings.isEmpty(result) ? rsmd.getColumnName(columnIndex) : result;
}
/**
* Returns the column index starts with from 1, not 0.
*
* @param resultSet
* @param columnName
* @return
* @throws UncheckedSQLException the unchecked SQL exception
*/
public static int getColumnIndex(final ResultSet resultSet, final String columnName) throws UncheckedSQLException {
try {
return getColumnIndex(resultSet.getMetaData(), columnName);
} catch (SQLException e) {
throw new UncheckedSQLException(e);
}
}
/**
* Returns the column index starts with from 1, not 0.
*
* @param rsmd
* @param columnName
* @return
* @throws SQLException
*/
public static int getColumnIndex(final ResultSetMetaData rsmd, final String columnName) throws SQLException {
final int columnCount = rsmd.getColumnCount();
String columnLabel = null;
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
columnLabel = rsmd.getColumnLabel(columnIndex);
if (columnLabel != null && columnLabel.equalsIgnoreCase(columnName)) {
return columnIndex;
}
columnLabel = rsmd.getColumnName(columnIndex);
if (columnLabel != null && columnLabel.equalsIgnoreCase(columnName)) {
return columnIndex;
}
}
return -1;
}
@FunctionalInterface
interface ColumnConverterByIndex {
Object apply(ResultSet rs, int columnIndex, Object columnValue) throws SQLException;
}
@FunctionalInterface
interface ColumnConverterByLabel {
Object apply(ResultSet rs, String columnLabel, Object columnValue) throws SQLException;
}
private static final Throwables.Function
*
* It's incorrect to use flag to identity the transaction should be committed or rolled back.
* Don't write below code:
*
*
* public void doSomethingA() {
* ...
* final SQLTransaction tranA = JdbcUtil.beginTransaction(dataSource1, isolation);
* boolean flagToCommit = false;
* try {
* // do your work with the conn...
* ...
* flagToCommit = true;
* } finally {
* if (flagToCommit) {
* tranA.commit();
* } else {
* tranA.rollbackIfNotCommitted();
* }
* }
* }
*
*
*
* @param dataSource
* @param isolationLevel
* @param isForUpdateOnly
* @return
* @throws UncheckedSQLException the unchecked SQL exception
* @see {@link #getConnection(javax.sql.DataSource)}
* @see {@link #releaseConnection(Connection, javax.sql.DataSource)}
* @see SQLExecutor#beginTransaction(IsolationLevel, boolean, JdbcSettings)
*/
public static SQLTransaction beginTransaction(final javax.sql.DataSource dataSource, final IsolationLevel isolationLevel, final boolean isForUpdateOnly)
throws UncheckedSQLException {
N.checkArgNotNull(dataSource, "dataSource");
N.checkArgNotNull(isolationLevel, "isolationLevel");
SQLTransaction tran = SQLTransaction.getTransaction(dataSource, CreatedBy.JDBC_UTIL);
if (tran == null) {
Connection conn = null;
boolean noException = false;
try { //NOSONAR
conn = getConnection(dataSource);
tran = new SQLTransaction(dataSource, conn, isolationLevel, CreatedBy.JDBC_UTIL, true); //NOSONAR
tran.incrementAndGetRef(isolationLevel, isForUpdateOnly);
noException = true;
} catch (SQLException e) {
throw new UncheckedSQLException(e);
} finally {
if (!noException) {
releaseConnection(conn, dataSource);
}
}
logger.info("Create a new SQLTransaction(id={})", tran.id());
SQLTransaction.putTransaction(tran);
} else {
logger.info("Reusing the existing SQLTransaction(id={})", tran.id());
tran.incrementAndGetRef(isolationLevel, isForUpdateOnly);
}
return tran;
}
/**
*
*
* @param
* @param
* @param dataSource
* @param cmd
* @return
* @throws IllegalArgumentException
* @throws E
*/
@Beta
public static T callInTransaction(final javax.sql.DataSource dataSource, final Throwables.Callable cmd)
throws IllegalArgumentException, E {
N.checkArgNotNull(dataSource, "dataSource");
N.checkArgNotNull(cmd, "cmd");
final SQLTransaction tran = JdbcUtil.beginTransaction(dataSource);
T result = null;
try {
result = cmd.call();
tran.commit();
} finally {
tran.rollbackIfNotCommitted();
}
return result;
}
/**
*
* @param
* @param
* @param dataSource
* @param cmd
* @return
* @throws E
*/
@Beta
public static T callInTransaction(final javax.sql.DataSource dataSource, final Throwables.Function cmd)
throws E {
N.checkArgNotNull(dataSource, "dataSource");
N.checkArgNotNull(cmd, "cmd");
final SQLTransaction tran = JdbcUtil.beginTransaction(dataSource);
T result = null;
try {
result = cmd.apply(tran.connection());
tran.commit();
} finally {
tran.rollbackIfNotCommitted();
}
return result;
}
/**
*
*
* @param
* @param dataSource
* @param cmd
* @throws IllegalArgumentException
* @throws E
*/
@Beta
public static void runInTransaction(final javax.sql.DataSource dataSource, final Throwables.Runnable cmd)
throws IllegalArgumentException, E {
N.checkArgNotNull(dataSource, "dataSource");
N.checkArgNotNull(cmd, "cmd");
final SQLTransaction tran = JdbcUtil.beginTransaction(dataSource);
try {
cmd.run();
tran.commit();
} finally {
tran.rollbackIfNotCommitted();
}
}
/**
*
*
* @param
* @param dataSource
* @param cmd
* @throws IllegalArgumentException
* @throws E
*/
@Beta
public static void runInTransaction(final javax.sql.DataSource dataSource, final Throwables.Consumer cmd)
throws IllegalArgumentException, E {
N.checkArgNotNull(dataSource, "dataSource");
N.checkArgNotNull(cmd, "cmd");
final SQLTransaction tran = JdbcUtil.beginTransaction(dataSource);
try {
cmd.accept(tran.connection());
tran.commit();
} finally {
tran.rollbackIfNotCommitted();
}
}
/**
*
*
* @param
* @param
* @param dataSource
* @param cmd
* @return
* @throws IllegalArgumentException
* @throws E
*/
@Beta
public static T callNotInStartedTransaction(final javax.sql.DataSource dataSource, final Throwables.Callable cmd)
throws IllegalArgumentException, E {
N.checkArgNotNull(dataSource, "dataSource");
N.checkArgNotNull(cmd, "cmd");
if (isInSpring && !isSpringTransactionalDisabled_TL.get()) { //NOSONAR
JdbcUtil.disableSpringTransactional(true);
final SQLTransaction tran = SQLTransaction.getTransaction(dataSource, CreatedBy.JDBC_UTIL);
try {
if (tran == null) {
return cmd.call();
} else {
return tran.callNotInMe(cmd);
}
} finally {
JdbcUtil.disableSpringTransactional(false);
}
} else {
final SQLTransaction tran = SQLTransaction.getTransaction(dataSource, CreatedBy.JDBC_UTIL);
if (tran == null) {
return cmd.call();
} else {
return tran.callNotInMe(cmd);
}
}
}
/**
*
*
* @param
* @param
* @param dataSource
* @param cmd
* @return
* @throws IllegalArgumentException
* @throws E
*/
@Beta
public static T callNotInStartedTransaction(final javax.sql.DataSource dataSource,
final Throwables.Function cmd) throws IllegalArgumentException, E {
N.checkArgNotNull(dataSource, "dataSource");
N.checkArgNotNull(cmd, "cmd");
if (isInSpring && !isSpringTransactionalDisabled_TL.get()) { //NOSONAR
JdbcUtil.disableSpringTransactional(true);
final SQLTransaction tran = SQLTransaction.getTransaction(dataSource, CreatedBy.JDBC_UTIL);
try {
if (tran == null) {
return cmd.apply(dataSource);
} else {
return tran.callNotInMe(() -> cmd.apply(dataSource));
}
} finally {
JdbcUtil.disableSpringTransactional(false);
}
} else {
final SQLTransaction tran = SQLTransaction.getTransaction(dataSource, CreatedBy.JDBC_UTIL);
if (tran == null) {
return cmd.apply(dataSource);
} else {
return tran.callNotInMe(() -> cmd.apply(dataSource));
}
}
}
/**
*
*
* @param
* @param dataSource
* @param cmd
* @throws IllegalArgumentException
* @throws E
*/
@Beta
public static void runNotInStartedTransaction(final javax.sql.DataSource dataSource, final Throwables.Runnable cmd)
throws IllegalArgumentException, E {
N.checkArgNotNull(dataSource, "dataSource");
N.checkArgNotNull(cmd, "cmd");
if (isInSpring && !isSpringTransactionalDisabled_TL.get()) { //NOSONAR
JdbcUtil.disableSpringTransactional(true);
final SQLTransaction tran = SQLTransaction.getTransaction(dataSource, CreatedBy.JDBC_UTIL);
try {
if (tran == null) {
cmd.run();
} else {
tran.runNotInMe(cmd);
}
} finally {
JdbcUtil.disableSpringTransactional(false);
}
} else {
final SQLTransaction tran = SQLTransaction.getTransaction(dataSource, CreatedBy.JDBC_UTIL);
if (tran == null) {
cmd.run();
} else {
tran.runNotInMe(cmd);
}
}
}
/**
*
*
* @param
* @param dataSource
* @param cmd
* @throws IllegalArgumentException
* @throws E
*/
@Beta
public static void runNotInStartedTransaction(final javax.sql.DataSource dataSource,
final Throwables.Consumer cmd) throws IllegalArgumentException, E {
N.checkArgNotNull(dataSource, "dataSource");
N.checkArgNotNull(cmd, "cmd");
if (isInSpring && !isSpringTransactionalDisabled_TL.get()) { //NOSONAR
JdbcUtil.disableSpringTransactional(true);
final SQLTransaction tran = SQLTransaction.getTransaction(dataSource, CreatedBy.JDBC_UTIL);
try {
if (tran == null) {
cmd.accept(dataSource);
} else {
tran.runNotInMe(() -> cmd.accept(dataSource));
}
} finally {
JdbcUtil.disableSpringTransactional(false);
}
} else {
final SQLTransaction tran = SQLTransaction.getTransaction(dataSource, CreatedBy.JDBC_UTIL);
if (tran == null) {
cmd.accept(dataSource);
} else {
tran.runNotInMe(() -> cmd.accept(dataSource));
}
}
}
/**
* Gets the SQL operation.
*
* @param sql
* @return
*/
static SQLOperation getSQLOperation(String sql) {
if (Strings.startsWithIgnoreCase(sql.trim(), "select ")) {
return SQLOperation.SELECT;
} else if (Strings.startsWithIgnoreCase(sql.trim(), "update ")) {
return SQLOperation.UPDATE;
} else if (Strings.startsWithIgnoreCase(sql.trim(), "insert ")) {
return SQLOperation.INSERT;
} else if (Strings.startsWithIgnoreCase(sql.trim(), "delete ")) {
return SQLOperation.DELETE;
} else if (Strings.startsWithIgnoreCase(sql.trim(), "merge ")) {
return SQLOperation.MERGE;
} else {
for (SQLOperation so : SQLOperation.values()) {
if (Strings.startsWithIgnoreCase(sql.trim(), so.name())) {
return so;
}
}
}
return SQLOperation.UNKNOWN;
}
static final Throwables.Consumer stmtSetterForBigQueryResult = stmt -> {
// stmt.setFetchDirectionToForward().setFetchSize(JdbcUtil.DEFAULT_FETCH_SIZE_FOR_BIG_RESULT);
stmt.setFetchDirection(ResultSet.FETCH_FORWARD);
if (stmt.getFetchSize() < JdbcUtil.DEFAULT_FETCH_SIZE_FOR_BIG_RESULT) {
stmt.setFetchSize(JdbcUtil.DEFAULT_FETCH_SIZE_FOR_BIG_RESULT);
}
};
static final Throwables.Consumer stmtSetterForStream = stmt -> {
stmt.setFetchDirection(ResultSet.FETCH_FORWARD);
if (stmt.getFetchSize() < JdbcUtil.DEFAULT_FETCH_SIZE_FOR_STREAM) {
stmt.setFetchSize(JdbcUtil.DEFAULT_FETCH_SIZE_FOR_STREAM);
}
};
/**
* If this method is called where a transaction is started by {@code JdbcUtil.beginTransaction} or in {@code Spring} with the same {@code DataSource} in the same thread,
* the {@code Connection} started the Transaction will be used here.
* Otherwise a {@code Connection} directly from the specified {@code DataSource}(Connection pool) will be borrowed and used.
*
* @param ds
* @param sql
* @return
* @throws IllegalArgumentException
* @throws SQLException
* @see #getConnection(javax.sql.DataSource)
* @see #releaseConnection(Connection, javax.sql.DataSource)
*/
public static PreparedQuery prepareQuery(final javax.sql.DataSource ds, final String sql) throws IllegalArgumentException, SQLException {
N.checkArgNotNull(ds, "dataSource");
N.checkArgNotEmpty(sql, "sql");
final SQLTransaction tran = getTransaction(ds, sql, CreatedBy.JDBC_UTIL);
if (tran != null) {
return prepareQuery(tran.connection(), sql);
} else {
PreparedQuery result = null;
Connection conn = null;
try {
conn = getConnection(ds);
result = prepareQuery(conn, sql).onClose(createCloseHandler(conn, ds));
} finally {
if (result == null) {
releaseConnection(conn, ds);
}
}
return result;
}
}
/**
* If this method is called where a transaction is started by {@code JdbcUtil.beginTransaction} or in {@code Spring} with the same {@code DataSource} in the same thread,
* the {@code Connection} started the Transaction will be used here.
* Otherwise a {@code Connection} directly from the specified {@code DataSource}(Connection pool) will be borrowed and used.
*
* @param ds
* @param sql
* @param autoGeneratedKeys
* @return
* @throws IllegalArgumentException
* @throws SQLException
* @see #getConnection(javax.sql.DataSource)
* @see #releaseConnection(Connection, javax.sql.DataSource)
*/
public static PreparedQuery prepareQuery(final javax.sql.DataSource ds, final String sql, final boolean autoGeneratedKeys)
throws IllegalArgumentException, SQLException {
N.checkArgNotNull(ds, "dataSource");
N.checkArgNotEmpty(sql, "sql");
final SQLTransaction tran = getTransaction(ds, sql, CreatedBy.JDBC_UTIL);
if (tran != null) {
return prepareQuery(tran.connection(), sql, autoGeneratedKeys);
} else {
PreparedQuery result = null;
Connection conn = null;
try {
conn = getConnection(ds);
result = prepareQuery(conn, sql, autoGeneratedKeys).onClose(createCloseHandler(conn, ds));
} finally {
if (result == null) {
releaseConnection(conn, ds);
}
}
return result;
}
}
/**
*
*
* @param ds
* @param sql
* @param returnColumnIndexes
* @return
* @throws IllegalArgumentException
* @throws SQLException
*/
public static PreparedQuery prepareQuery(final javax.sql.DataSource ds, final String sql, final int[] returnColumnIndexes)
throws IllegalArgumentException, SQLException {
N.checkArgNotNull(ds, "dataSource");
N.checkArgNotEmpty(sql, "sql");
N.checkArgNotEmpty(returnColumnIndexes, "returnColumnIndexes");
final SQLTransaction tran = getTransaction(ds, sql, CreatedBy.JDBC_UTIL);
if (tran != null) {
return prepareQuery(tran.connection(), sql, returnColumnIndexes);
} else {
PreparedQuery result = null;
Connection conn = null;
try {
conn = getConnection(ds);
result = prepareQuery(conn, sql, returnColumnIndexes).onClose(createCloseHandler(conn, ds));
} finally {
if (result == null) {
releaseConnection(conn, ds);
}
}
return result;
}
}
/**
*
*
* @param ds
* @param sql
* @param returnColumnNames
* @return
* @throws IllegalArgumentException
* @throws SQLException
*/
public static PreparedQuery prepareQuery(final javax.sql.DataSource ds, final String sql, final String[] returnColumnNames)
throws IllegalArgumentException, SQLException {
N.checkArgNotNull(ds, "dataSource");
N.checkArgNotEmpty(sql, "sql");
N.checkArgNotEmpty(returnColumnNames, "returnColumnNames");
final SQLTransaction tran = getTransaction(ds, sql, CreatedBy.JDBC_UTIL);
if (tran != null) {
return prepareQuery(tran.connection(), sql, returnColumnNames);
} else {
PreparedQuery result = null;
Connection conn = null;
try {
conn = getConnection(ds);
result = prepareQuery(conn, sql, returnColumnNames).onClose(createCloseHandler(conn, ds));
} finally {
if (result == null) {
releaseConnection(conn, ds);
}
}
return result;
}
}
/**
* If this method is called where a transaction is started by {@code JdbcUtil.beginTransaction} or in {@code Spring} with the same {@code DataSource} in the same thread,
* the {@code Connection} started the Transaction will be used here.
* Otherwise a {@code Connection} directly from the specified {@code DataSource}(Connection pool) will be borrowed and used.
*
* @param ds
* @param sql
* @param stmtCreator the created {@code PreparedStatement} will be closed after any execution methods in {@code PreparedQuery/CallableQuery} is called.
* An execution method is a method which will trigger the backed {@code PreparedStatement/CallableStatement} to be executed, for example: get/query/queryForInt/Long/../findFirst/findOnlyOne/list/execute/....
* @return
* @throws IllegalArgumentException
* @throws SQLException
* @see #getConnection(javax.sql.DataSource)
* @see #releaseConnection(Connection, javax.sql.DataSource)
*/
public static PreparedQuery prepareQuery(final javax.sql.DataSource ds, final String sql,
final Throwables.BiFunction stmtCreator) throws IllegalArgumentException, SQLException {
N.checkArgNotNull(ds, "dataSource");
N.checkArgNotEmpty(sql, "sql");
N.checkArgNotNull(stmtCreator, "stmtCreator");
final SQLTransaction tran = getTransaction(ds, sql, CreatedBy.JDBC_UTIL);
if (tran != null) {
return prepareQuery(tran.connection(), sql, stmtCreator);
} else {
PreparedQuery result = null;
Connection conn = null;
try {
conn = getConnection(ds);
result = prepareQuery(conn, sql, stmtCreator).onClose(createCloseHandler(conn, ds));
} finally {
if (result == null) {
releaseConnection(conn, ds);
}
}
return result;
}
}
/**
* Never write below code because it will definitely cause {@code Connection} leak:
*
*
* @param conn the specified {@code conn} won't be close after this query is executed.
* @param sql
* @return
* @throws IllegalArgumentException
* @throws SQLException
*/
public static PreparedQuery prepareQuery(final Connection conn, final String sql) throws IllegalArgumentException, SQLException {
N.checkArgNotNull(conn, "conn");
N.checkArgNotEmpty(sql, "sql");
return new PreparedQuery(prepareStatement(conn, sql));
}
/**
* Never write below code because it will definitely cause {@code Connection} leak:
*
*
* @param conn the specified {@code conn} won't be close after this query is executed.
* @param sql
* @param autoGeneratedKeys
* @return
* @throws IllegalArgumentException
* @throws SQLException
*/
public static PreparedQuery prepareQuery(final Connection conn, final String sql, final boolean autoGeneratedKeys)
throws IllegalArgumentException, SQLException {
N.checkArgNotNull(conn, "conn");
N.checkArgNotEmpty(sql, "sql");
return new PreparedQuery(prepareStatement(conn, sql, autoGeneratedKeys));
}
/**
* Never write below code because it will definitely cause {@code Connection} leak:
*
*
* @param conn the specified {@code conn} won't be close after this query is executed.
* @param sql
* @param stmtCreator the created {@code PreparedStatement} will be closed after any execution methods in {@code PreparedQuery/CallableQuery} is called.
* An execution method is a method which will trigger the backed {@code PreparedStatement/CallableStatement} to be executed, for example: get/query/queryForInt/Long/../findFirst/findOnlyOne/list/execute/....
* @return
* @throws IllegalArgumentException
* @throws SQLException
*/
public static PreparedQuery prepareQuery(final Connection conn, final String sql,
final Throwables.BiFunction stmtCreator) throws IllegalArgumentException, SQLException {
N.checkArgNotNull(conn, "conn");
N.checkArgNotEmpty(sql, "sql");
N.checkArgNotNull(stmtCreator, "stmtCreator");
return new PreparedQuery(prepareStatement(conn, sql, stmtCreator));
}
/**
* Prepare {@code select} query for big result set. Fetch direction will be set to {@code FetchDirection.FORWARD}
* and fetch size will be set to {@code DEFAULT_FETCH_SIZE_FOR_BIG_RESULT=1000}.
*
* @param ds
* @param sql
* @return
* @throws SQLException
*/
@Beta
public static PreparedQuery prepareQueryForBigResult(final javax.sql.DataSource ds, final String sql) throws SQLException {
return prepareQuery(ds, sql).configStmt(stmtSetterForBigQueryResult);
}
/**
* Prepare {@code select} query for big result set. Fetch direction will be set to {@code FetchDirection.FORWARD}
* and fetch size will be set to {@code DEFAULT_FETCH_SIZE_FOR_BIG_RESULT=1000}.
*
* @param conn
* @param sql
* @return
* @throws SQLException
*/
@Beta
public static PreparedQuery prepareQueryForBigResult(final Connection conn, final String sql) throws SQLException {
return prepareQuery(conn, sql).configStmt(stmtSetterForBigQueryResult);
}
/**
* If this method is called where a transaction is started by {@code JdbcUtil.beginTransaction} or in {@code Spring} with the same {@code DataSource} in the same thread,
* the {@code Connection} started the Transaction will be used here.
* Otherwise a {@code Connection} directly from the specified {@code DataSource}(Connection pool) will be borrowed and used.
*
* @param ds
* @param namedSql for example {@code SELECT first_name, last_name FROM account where id = :id}
* @return
* @throws IllegalArgumentException
* @throws SQLException
* @see #getConnection(javax.sql.DataSource)
* @see #releaseConnection(Connection, javax.sql.DataSource)
*/
public static NamedQuery prepareNamedQuery(final javax.sql.DataSource ds, final String namedSql) throws IllegalArgumentException, SQLException {
N.checkArgNotNull(ds, "dataSource");
N.checkArgNotEmpty(namedSql, "namedSql");
final SQLTransaction tran = getTransaction(ds, namedSql, CreatedBy.JDBC_UTIL);
if (tran != null) {
return prepareNamedQuery(tran.connection(), namedSql);
} else {
NamedQuery result = null;
Connection conn = null;
try {
conn = getConnection(ds);
result = prepareNamedQuery(conn, namedSql).onClose(createCloseHandler(conn, ds));
} finally {
if (result == null) {
releaseConnection(conn, ds);
}
}
return result;
}
}
/**
* If this method is called where a transaction is started by {@code JdbcUtil.beginTransaction} or in {@code Spring} with the same {@code DataSource} in the same thread,
* the {@code Connection} started the Transaction will be used here.
* Otherwise a {@code Connection} directly from the specified {@code DataSource}(Connection pool) will be borrowed and used.
*
* @param ds
* @param namedSql for example {@code SELECT first_name, last_name FROM account where id = :id}
* @param autoGeneratedKeys
* @return
* @throws IllegalArgumentException
* @throws SQLException
* @see #getConnection(javax.sql.DataSource)
* @see #releaseConnection(Connection, javax.sql.DataSource)
*/
public static NamedQuery prepareNamedQuery(final javax.sql.DataSource ds, final String namedSql, final boolean autoGeneratedKeys)
throws IllegalArgumentException, SQLException {
N.checkArgNotNull(ds, "dataSource");
N.checkArgNotEmpty(namedSql, "namedSql");
final SQLTransaction tran = getTransaction(ds, namedSql, CreatedBy.JDBC_UTIL);
if (tran != null) {
return prepareNamedQuery(tran.connection(), namedSql, autoGeneratedKeys);
} else {
NamedQuery result = null;
Connection conn = null;
try {
conn = getConnection(ds);
result = prepareNamedQuery(conn, namedSql, autoGeneratedKeys).onClose(createCloseHandler(conn, ds));
} finally {
if (result == null) {
releaseConnection(conn, ds);
}
}
return result;
}
}
/**
* If this method is called where a transaction is started by {@code JdbcUtil.beginTransaction} or in {@code Spring} with the same {@code DataSource} in the same thread,
* the {@code Connection} started the Transaction will be used here.
* Otherwise a {@code Connection} directly from the specified {@code DataSource}(Connection pool) will be borrowed and used.
*
* @param ds
* @param namedSql for example {@code SELECT first_name, last_name FROM account where id = :id}
* @param returnColumnIndexes
* @return
* @throws IllegalArgumentException
* @throws SQLException
*/
public static NamedQuery prepareNamedQuery(final javax.sql.DataSource ds, final String namedSql, final int[] returnColumnIndexes)
throws IllegalArgumentException, SQLException {
N.checkArgNotNull(ds, "dataSource");
N.checkArgNotEmpty(namedSql, "namedSql");
N.checkArgNotEmpty(returnColumnIndexes, "returnColumnIndexes");
final SQLTransaction tran = getTransaction(ds, namedSql, CreatedBy.JDBC_UTIL);
if (tran != null) {
return prepareNamedQuery(tran.connection(), namedSql, returnColumnIndexes);
} else {
NamedQuery result = null;
Connection conn = null;
try {
conn = getConnection(ds);
result = prepareNamedQuery(conn, namedSql, returnColumnIndexes).onClose(createCloseHandler(conn, ds));
} finally {
if (result == null) {
releaseConnection(conn, ds);
}
}
return result;
}
}
/**
* If this method is called where a transaction is started by {@code JdbcUtil.beginTransaction} or in {@code Spring} with the same {@code DataSource} in the same thread,
* the {@code Connection} started the Transaction will be used here.
* Otherwise a {@code Connection} directly from the specified {@code DataSource}(Connection pool) will be borrowed and used.
*
* @param ds
* @param namedSql for example {@code SELECT first_name, last_name FROM account where id = :id}
* @param returnColumnNames
* @return
* @throws IllegalArgumentException
* @throws SQLException
*/
public static NamedQuery prepareNamedQuery(final javax.sql.DataSource ds, final String namedSql, final String[] returnColumnNames)
throws IllegalArgumentException, SQLException {
N.checkArgNotNull(ds, "dataSource");
N.checkArgNotEmpty(namedSql, "namedSql");
N.checkArgNotEmpty(returnColumnNames, "returnColumnNames");
final SQLTransaction tran = getTransaction(ds, namedSql, CreatedBy.JDBC_UTIL);
if (tran != null) {
return prepareNamedQuery(tran.connection(), namedSql, returnColumnNames);
} else {
NamedQuery result = null;
Connection conn = null;
try {
conn = getConnection(ds);
result = prepareNamedQuery(conn, namedSql, returnColumnNames).onClose(createCloseHandler(conn, ds));
} finally {
if (result == null) {
releaseConnection(conn, ds);
}
}
return result;
}
}
/**
* If this method is called where a transaction is started by {@code JdbcUtil.beginTransaction} or in {@code Spring} with the same {@code DataSource} in the same thread,
* the {@code Connection} started the Transaction will be used here.
* Otherwise a {@code Connection} directly from the specified {@code DataSource}(Connection pool) will be borrowed and used.
*
* @param ds
* @param namedSql for example {@code SELECT first_name, last_name FROM account where id = :id}
* @param stmtCreator the created {@code PreparedStatement} will be closed after any execution methods in {@code NamedQuery/CallableQuery} is called.
* An execution method is a method which will trigger the backed {@code PreparedStatement/CallableStatement} to be executed, for example: get/query/queryForInt/Long/../findFirst/findOnlyOne/list/execute/....
* @return
* @throws IllegalArgumentException
* @throws SQLException
* @see #getConnection(javax.sql.DataSource)
* @see #releaseConnection(Connection, javax.sql.DataSource)
*/
public static NamedQuery prepareNamedQuery(final javax.sql.DataSource ds, final String namedSql,
final Throwables.BiFunction stmtCreator) throws IllegalArgumentException, SQLException {
N.checkArgNotNull(ds, "dataSource");
N.checkArgNotEmpty(namedSql, "namedSql");
N.checkArgNotNull(stmtCreator, "stmtCreator");
final SQLTransaction tran = getTransaction(ds, namedSql, CreatedBy.JDBC_UTIL);
if (tran != null) {
return prepareNamedQuery(tran.connection(), namedSql, stmtCreator);
} else {
NamedQuery result = null;
Connection conn = null;
try {
conn = getConnection(ds);
result = prepareNamedQuery(conn, namedSql, stmtCreator).onClose(createCloseHandler(conn, ds));
} finally {
if (result == null) {
releaseConnection(conn, ds);
}
}
return result;
}
}
/**
* Never write below code because it will definitely cause {@code Connection} leak:
*
*
* @param conn the specified {@code conn} won't be close after this query is executed.
* @param namedSql for example {@code SELECT first_name, last_name FROM account where id = :id}
* @return
* @throws IllegalArgumentException
* @throws SQLException
*/
public static NamedQuery prepareNamedQuery(final Connection conn, final String namedSql) throws IllegalArgumentException, SQLException {
N.checkArgNotNull(conn, "conn");
N.checkArgNotEmpty(namedSql, "namedSql");
final ParsedSql parsedSql = parseNamedSql(namedSql);
return new NamedQuery(prepareStatement(conn, parsedSql), parsedSql);
}
/**
* Never write below code because it will definitely cause {@code Connection} leak:
*
*
* @param conn the specified {@code conn} won't be close after this query is executed.
* @param namedSql for example {@code SELECT first_name, last_name FROM account where id = :id}
* @param autoGeneratedKeys
* @return
* @throws IllegalArgumentException
* @throws SQLException
*/
public static NamedQuery prepareNamedQuery(final Connection conn, final String namedSql, final boolean autoGeneratedKeys)
throws IllegalArgumentException, SQLException {
N.checkArgNotNull(conn, "conn");
N.checkArgNotEmpty(namedSql, "namedSql");
final ParsedSql parsedSql = parseNamedSql(namedSql);
return new NamedQuery(prepareStatement(conn, parsedSql, autoGeneratedKeys), parsedSql);
}
/**
* Never write below code because it will definitely cause {@code Connection} leak:
*
*
* @param conn the specified {@code conn} won't be close after this query is executed.
* @param namedSql for example {@code SELECT first_name, last_name FROM account where id = :id}
* @param returnColumnIndexes
* @return
* @throws IllegalArgumentException
* @throws SQLException
*/
public static NamedQuery prepareNamedQuery(final Connection conn, final String namedSql, final int[] returnColumnIndexes)
throws IllegalArgumentException, SQLException {
N.checkArgNotNull(conn, "conn");
N.checkArgNotEmpty(namedSql, "namedSql");
N.checkArgNotEmpty(returnColumnIndexes, "returnColumnIndexes");
final ParsedSql parsedSql = parseNamedSql(namedSql);
return new NamedQuery(prepareStatement(conn, parsedSql, returnColumnIndexes), parsedSql);
}
/**
* Never write below code because it will definitely cause {@code Connection} leak:
*
*
* @param conn the specified {@code conn} won't be close after this query is executed.
* @param namedSql for example {@code SELECT first_name, last_name FROM account where id = :id}
* @param returnColumnNames
* @return
* @throws IllegalArgumentException
* @throws SQLException
*/
public static NamedQuery prepareNamedQuery(final Connection conn, final String namedSql, final String[] returnColumnNames)
throws IllegalArgumentException, SQLException {
N.checkArgNotNull(conn, "conn");
N.checkArgNotEmpty(namedSql, "namedSql");
N.checkArgNotEmpty(returnColumnNames, "returnColumnNames");
final ParsedSql parsedSql = parseNamedSql(namedSql);
return new NamedQuery(prepareStatement(conn, parsedSql, returnColumnNames), parsedSql);
}
/**
* Never write below code because it will definitely cause {@code Connection} leak:
*
*
* @param conn the specified {@code conn} won't be close after this query is executed.
* @param namedSql for example {@code SELECT first_name, last_name FROM account where id = :id}
* @param stmtCreator the created {@code PreparedStatement} will be closed after any execution methods in {@code NamedQuery/CallableQuery} is called.
* An execution method is a method which will trigger the backed {@code PreparedStatement/CallableStatement} to be executed, for example: get/query/queryForInt/Long/../findFirst/findOnlyOne/list/execute/....
* @return
* @throws IllegalArgumentException
* @throws SQLException
*/
public static NamedQuery prepareNamedQuery(final Connection conn, final String namedSql,
final Throwables.BiFunction stmtCreator) throws IllegalArgumentException, SQLException {
N.checkArgNotNull(conn, "conn");
N.checkArgNotEmpty(namedSql, "namedSql");
N.checkArgNotNull(stmtCreator, "stmtCreator");
final ParsedSql parsedSql = parseNamedSql(namedSql);
return new NamedQuery(prepareStatement(conn, parsedSql, stmtCreator), parsedSql);
}
/**
* If this method is called where a transaction is started by {@code JdbcUtil.beginTransaction} or in {@code Spring} with the same {@code DataSource} in the same thread,
* the {@code Connection} started the Transaction will be used here.
* Otherwise a {@code Connection} directly from the specified {@code DataSource}(Connection pool) will be borrowed and used.
*
* @param ds
* @param namedSql for example {@code SELECT first_name, last_name FROM account where id = :id}
* @return
* @throws IllegalArgumentException
* @throws SQLException
* @see #getConnection(javax.sql.DataSource)
* @see #releaseConnection(Connection, javax.sql.DataSource)
*/
public static NamedQuery prepareNamedQuery(final javax.sql.DataSource ds, final ParsedSql namedSql) throws IllegalArgumentException, SQLException {
N.checkArgNotNull(ds, "dataSource");
N.checkArgNotNull(namedSql, "namedSql");
validateNamedSql(namedSql);
final SQLTransaction tran = getTransaction(ds, namedSql.getParameterizedSql(), CreatedBy.JDBC_UTIL);
if (tran != null) {
return prepareNamedQuery(tran.connection(), namedSql);
} else {
NamedQuery result = null;
Connection conn = null;
try {
conn = getConnection(ds);
result = prepareNamedQuery(conn, namedSql).onClose(createCloseHandler(conn, ds));
} finally {
if (result == null) {
releaseConnection(conn, ds);
}
}
return result;
}
}
/**
* If this method is called where a transaction is started by {@code JdbcUtil.beginTransaction} or in {@code Spring} with the same {@code DataSource} in the same thread,
* the {@code Connection} started the Transaction will be used here.
* Otherwise a {@code Connection} directly from the specified {@code DataSource}(Connection pool) will be borrowed and used.
*
* @param ds
* @param namedSql for example {@code SELECT first_name, last_name FROM account where id = :id}
* @param autoGeneratedKeys
* @return
* @throws IllegalArgumentException
* @throws SQLException
* @see #getConnection(javax.sql.DataSource)
* @see #releaseConnection(Connection, javax.sql.DataSource)
*/
public static NamedQuery prepareNamedQuery(final javax.sql.DataSource ds, final ParsedSql namedSql, final boolean autoGeneratedKeys)
throws IllegalArgumentException, SQLException {
N.checkArgNotNull(ds, "dataSource");
N.checkArgNotNull(namedSql, "namedSql");
validateNamedSql(namedSql);
final SQLTransaction tran = getTransaction(ds, namedSql.getParameterizedSql(), CreatedBy.JDBC_UTIL);
if (tran != null) {
return prepareNamedQuery(tran.connection(), namedSql, autoGeneratedKeys);
} else {
NamedQuery result = null;
Connection conn = null;
try {
conn = getConnection(ds);
result = prepareNamedQuery(conn, namedSql, autoGeneratedKeys).onClose(createCloseHandler(conn, ds));
} finally {
if (result == null) {
releaseConnection(conn, ds);
}
}
return result;
}
}
/**
* If this method is called where a transaction is started by {@code JdbcUtil.beginTransaction} or in {@code Spring} with the same {@code DataSource} in the same thread,
* the {@code Connection} started the Transaction will be used here.
* Otherwise a {@code Connection} directly from the specified {@code DataSource}(Connection pool) will be borrowed and used.
*
* @param ds
* @param namedSql for example {@code SELECT first_name, last_name FROM account where id = :id}
* @param returnColumnIndexes
* @return
* @throws IllegalArgumentException
* @throws SQLException
*/
public static NamedQuery prepareNamedQuery(final javax.sql.DataSource ds, final ParsedSql namedSql, final int[] returnColumnIndexes)
throws IllegalArgumentException, SQLException {
N.checkArgNotNull(ds, "dataSource");
N.checkArgNotNull(namedSql, "namedSql");
N.checkArgNotEmpty(returnColumnIndexes, "returnColumnIndexes");
validateNamedSql(namedSql);
final SQLTransaction tran = getTransaction(ds, namedSql.getParameterizedSql(), CreatedBy.JDBC_UTIL);
if (tran != null) {
return prepareNamedQuery(tran.connection(), namedSql, returnColumnIndexes);
} else {
NamedQuery result = null;
Connection conn = null;
try {
conn = getConnection(ds);
result = prepareNamedQuery(conn, namedSql, returnColumnIndexes).onClose(createCloseHandler(conn, ds));
} finally {
if (result == null) {
releaseConnection(conn, ds);
}
}
return result;
}
}
/**
* If this method is called where a transaction is started by {@code JdbcUtil.beginTransaction} or in {@code Spring} with the same {@code DataSource} in the same thread,
* the {@code Connection} started the Transaction will be used here.
* Otherwise a {@code Connection} directly from the specified {@code DataSource}(Connection pool) will be borrowed and used.
*
* @param ds
* @param namedSql for example {@code SELECT first_name, last_name FROM account where id = :id}
* @param returnColumnNames
* @return
* @throws IllegalArgumentException
* @throws SQLException
*/
public static NamedQuery prepareNamedQuery(final javax.sql.DataSource ds, final ParsedSql namedSql, final String[] returnColumnNames)
throws IllegalArgumentException, SQLException {
N.checkArgNotNull(ds, "dataSource");
N.checkArgNotNull(namedSql, "namedSql");
N.checkArgNotEmpty(returnColumnNames, "returnColumnNames");
validateNamedSql(namedSql);
final SQLTransaction tran = getTransaction(ds, namedSql.getParameterizedSql(), CreatedBy.JDBC_UTIL);
if (tran != null) {
return prepareNamedQuery(tran.connection(), namedSql, returnColumnNames);
} else {
NamedQuery result = null;
Connection conn = null;
try {
conn = getConnection(ds);
result = prepareNamedQuery(conn, namedSql, returnColumnNames).onClose(createCloseHandler(conn, ds));
} finally {
if (result == null) {
releaseConnection(conn, ds);
}
}
return result;
}
}
/**
* If this method is called where a transaction is started by {@code JdbcUtil.beginTransaction} or in {@code Spring} with the same {@code DataSource} in the same thread,
* the {@code Connection} started the Transaction will be used here.
* Otherwise a {@code Connection} directly from the specified {@code DataSource}(Connection pool) will be borrowed and used.
*
* @param ds
* @param namedSql for example {@code SELECT first_name, last_name FROM account where id = :id}
* @param stmtCreator the created {@code PreparedStatement} will be closed after any execution methods in {@code NamedQuery/CallableQuery} is called.
* An execution method is a method which will trigger the backed {@code PreparedStatement/CallableStatement} to be executed, for example: get/query/queryForInt/Long/../findFirst/findOnlyOne/list/execute/....
* @return
* @throws IllegalArgumentException
* @throws SQLException
* @see #getConnection(javax.sql.DataSource)
* @see #releaseConnection(Connection, javax.sql.DataSource)
*/
public static NamedQuery prepareNamedQuery(final javax.sql.DataSource ds, final ParsedSql namedSql,
final Throwables.BiFunction stmtCreator) throws IllegalArgumentException, SQLException {
N.checkArgNotNull(ds, "dataSource");
N.checkArgNotNull(namedSql, "namedSql");
N.checkArgNotNull(stmtCreator, "stmtCreator");
validateNamedSql(namedSql);
final SQLTransaction tran = getTransaction(ds, namedSql.getParameterizedSql(), CreatedBy.JDBC_UTIL);
if (tran != null) {
return prepareNamedQuery(tran.connection(), namedSql, stmtCreator);
} else {
NamedQuery result = null;
Connection conn = null;
try {
conn = getConnection(ds);
result = prepareNamedQuery(conn, namedSql, stmtCreator).onClose(createCloseHandler(conn, ds));
} finally {
if (result == null) {
releaseConnection(conn, ds);
}
}
return result;
}
}
/**
* Never write below code because it will definitely cause {@code Connection} leak:
*
*
* @param conn the specified {@code conn} won't be close after this query is executed.
* @param namedSql for example {@code SELECT first_name, last_name FROM account where id = :id}
* @return
* @throws IllegalArgumentException
* @throws SQLException
*/
public static NamedQuery prepareNamedQuery(final Connection conn, final ParsedSql namedSql) throws IllegalArgumentException, SQLException {
N.checkArgNotNull(conn, "conn");
N.checkArgNotNull(namedSql, "namedSql");
validateNamedSql(namedSql);
return new NamedQuery(prepareStatement(conn, namedSql), namedSql);
}
/**
* Never write below code because it will definitely cause {@code Connection} leak:
*
*
* @param conn the specified {@code conn} won't be close after this query is executed.
* @param namedSql for example {@code SELECT first_name, last_name FROM account where id = :id}
* @param autoGeneratedKeys
* @return
* @throws IllegalArgumentException
* @throws SQLException
*/
public static NamedQuery prepareNamedQuery(final Connection conn, final ParsedSql namedSql, final boolean autoGeneratedKeys)
throws IllegalArgumentException, SQLException {
N.checkArgNotNull(conn, "conn");
N.checkArgNotNull(namedSql, "namedSql");
validateNamedSql(namedSql);
return new NamedQuery(prepareStatement(conn, namedSql, autoGeneratedKeys), namedSql);
}
/**
* Never write below code because it will definitely cause {@code Connection} leak:
*
*
* @param conn the specified {@code conn} won't be close after this query is executed.
* @param namedSql for example {@code SELECT first_name, last_name FROM account where id = :id}
* @param returnColumnIndexes
* @return
* @throws IllegalArgumentException
* @throws SQLException
*/
public static NamedQuery prepareNamedQuery(final Connection conn, final ParsedSql namedSql, final int[] returnColumnIndexes)
throws IllegalArgumentException, SQLException {
N.checkArgNotNull(conn, "conn");
N.checkArgNotNull(namedSql, "namedSql");
N.checkArgNotEmpty(returnColumnIndexes, "returnColumnIndexes");
validateNamedSql(namedSql);
return new NamedQuery(prepareStatement(conn, namedSql, returnColumnIndexes), namedSql);
}
/**
* Never write below code because it will definitely cause {@code Connection} leak:
*
*
* @param conn the specified {@code conn} won't be close after this query is executed.
* @param namedSql for example {@code SELECT first_name, last_name FROM account where id = :id}
* @param returnColumnNames
* @return
* @throws IllegalArgumentException
* @throws SQLException
*/
public static NamedQuery prepareNamedQuery(final Connection conn, final ParsedSql namedSql, final String[] returnColumnNames)
throws IllegalArgumentException, SQLException {
N.checkArgNotNull(conn, "conn");
N.checkArgNotNull(namedSql, "namedSql");
N.checkArgNotEmpty(returnColumnNames, "returnColumnNames");
validateNamedSql(namedSql);
return new NamedQuery(prepareStatement(conn, namedSql, returnColumnNames), namedSql);
}
/**
* Never write below code because it will definitely cause {@code Connection} leak:
*
*
* @param conn the specified {@code conn} won't be close after this query is executed.
* @param namedSql for example {@code SELECT first_name, last_name FROM account where id = :id}
* @param stmtCreator the created {@code PreparedStatement} will be closed after any execution methods in {@code NamedQuery/CallableQuery} is called.
* An execution method is a method which will trigger the backed {@code PreparedStatement/CallableStatement} to be executed, for example: get/query/queryForInt/Long/../findFirst/findOnlyOne/list/execute/....
* @return
* @throws IllegalArgumentException
* @throws SQLException
*/
public static NamedQuery prepareNamedQuery(final Connection conn, final ParsedSql namedSql,
final Throwables.BiFunction stmtCreator) throws IllegalArgumentException, SQLException {
N.checkArgNotNull(conn, "conn");
N.checkArgNotNull(namedSql, "namedSql");
N.checkArgNotNull(stmtCreator, "stmtCreator");
validateNamedSql(namedSql);
return new NamedQuery(prepareStatement(conn, namedSql, stmtCreator), namedSql);
}
/**
* Prepare {@code select} query for big result set. Fetch direction will be set to {@code FetchDirection.FORWARD}
* and fetch size will be set to {@code DEFAULT_FETCH_SIZE_FOR_BIG_RESULT=1000}.
*
* @param ds
* @param namedSql
* @return
* @throws SQLException
*/
@Beta
public static NamedQuery prepareNamedQueryForBigResult(final javax.sql.DataSource ds, final String namedSql) throws SQLException {
return prepareNamedQuery(ds, namedSql).configStmt(stmtSetterForBigQueryResult);
}
/**
* Prepare {@code select} query for big result set. Fetch direction will be set to {@code FetchDirection.FORWARD}
* and fetch size will be set to {@code DEFAULT_FETCH_SIZE_FOR_BIG_RESULT=1000}.
*
* @param ds
* @param namedSql
* @return
* @throws SQLException
*/
@Beta
public static NamedQuery prepareNamedQueryForBigResult(final javax.sql.DataSource ds, final ParsedSql namedSql) throws SQLException {
return prepareNamedQuery(ds, namedSql).configStmt(stmtSetterForBigQueryResult);
}
/**
* Prepare {@code select} query for big result set. Fetch direction will be set to {@code FetchDirection.FORWARD}
* and fetch size will be set to {@code DEFAULT_FETCH_SIZE_FOR_BIG_RESULT=1000}.
*
* @param conn
* @param namedSql
* @return
* @throws SQLException
*/
@Beta
public static NamedQuery prepareNamedQueryForBigResult(final Connection conn, final String namedSql) throws SQLException {
return prepareNamedQuery(conn, namedSql).configStmt(stmtSetterForBigQueryResult);
}
/**
* If this method is called where a transaction is started by {@code JdbcUtil.beginTransaction} or in {@code Spring} with the same {@code DataSource} in the same thread,
* the {@code Connection} started the Transaction will be used here.
* Otherwise a {@code Connection} directly from the specified {@code DataSource}(Connection pool) will be borrowed and used.
*
* @param ds
* @param sql
* @return
* @throws IllegalArgumentException
* @throws SQLException
* @see #getConnection(javax.sql.DataSource)
* @see #releaseConnection(Connection, javax.sql.DataSource)
*/
public static CallableQuery prepareCallableQuery(final javax.sql.DataSource ds, final String sql) throws IllegalArgumentException, SQLException {
N.checkArgNotNull(ds, "dataSource");
N.checkArgNotEmpty(sql, "sql");
final SQLTransaction tran = getTransaction(ds, sql, CreatedBy.JDBC_UTIL);
if (tran != null) {
return prepareCallableQuery(tran.connection(), sql);
} else {
CallableQuery result = null;
Connection conn = null;
try {
conn = getConnection(ds);
result = prepareCallableQuery(conn, sql).onClose(createCloseHandler(conn, ds));
} finally {
if (result == null) {
releaseConnection(conn, ds);
}
}
return result;
}
}
/**
* If this method is called where a transaction is started by {@code JdbcUtil.beginTransaction} or in {@code Spring} with the same {@code DataSource} in the same thread,
* the {@code Connection} started the Transaction will be used here.
* Otherwise a {@code Connection} directly from the specified {@code DataSource}(Connection pool) will be borrowed and used.
*
* @param ds
* @param sql
* @param stmtCreator the created {@code CallableStatement} will be closed after any execution methods in {@code PreparedQuery/CallableQuery} is called.
* An execution method is a method which will trigger the backed {@code PreparedStatement/CallableStatement} to be executed, for example: get/query/queryForInt/Long/../findFirst/findOnlyOne/list/execute/....
* @return
* @throws IllegalArgumentException
* @throws SQLException
* @see #getConnection(javax.sql.DataSource)
* @see #releaseConnection(Connection, javax.sql.DataSource)
*/
public static CallableQuery prepareCallableQuery(final javax.sql.DataSource ds, final String sql,
final Throwables.BiFunction stmtCreator) throws IllegalArgumentException, SQLException {
N.checkArgNotNull(ds, "dataSource");
N.checkArgNotEmpty(sql, "sql");
N.checkArgNotNull(stmtCreator, "stmtCreator");
final SQLTransaction tran = getTransaction(ds, sql, CreatedBy.JDBC_UTIL);
if (tran != null) {
return prepareCallableQuery(tran.connection(), sql, stmtCreator);
} else {
CallableQuery result = null;
Connection conn = null;
try {
conn = getConnection(ds);
result = prepareCallableQuery(conn, sql, stmtCreator).onClose(createCloseHandler(conn, ds));
} finally {
if (result == null) {
releaseConnection(conn, ds);
}
}
return result;
}
}
/**
* Never write below code because it will definitely cause {@code Connection} leak:
*