All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.landawn.abacus.util.JdbcUtil Maven / Gradle / Ivy

/*
 * 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.util;

import static com.landawn.abacus.dataSource.DataSourceConfiguration.DRIVER;
import static com.landawn.abacus.dataSource.DataSourceConfiguration.PASSWORD;
import static com.landawn.abacus.dataSource.DataSourceConfiguration.URL;
import static com.landawn.abacus.dataSource.DataSourceConfiguration.USER;
import static com.landawn.abacus.util.IOUtil.DEFAULT_QUEUE_SIZE_FOR_ROW_PARSER;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.Date;
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.SQLType;
import java.sql.Statement;
import java.sql.Time;
import java.sql.Timestamp;
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.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

import javax.xml.parsers.DocumentBuilder;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import com.landawn.abacus.DataSet;
import com.landawn.abacus.DataSource;
import com.landawn.abacus.DataSourceManager;
import com.landawn.abacus.DirtyMarker;
import com.landawn.abacus.EntityId;
import com.landawn.abacus.IsolationLevel;
import com.landawn.abacus.annotation.Beta;
import com.landawn.abacus.annotation.Internal;
import com.landawn.abacus.condition.Condition;
import com.landawn.abacus.condition.ConditionFactory.CF;
import com.landawn.abacus.core.DirtyMarkerUtil;
import com.landawn.abacus.core.RowDataSet;
import com.landawn.abacus.core.Seid;
import com.landawn.abacus.dataSource.DataSourceConfiguration;
import com.landawn.abacus.dataSource.DataSourceManagerConfiguration;
import com.landawn.abacus.dataSource.SQLDataSource;
import com.landawn.abacus.dataSource.SQLDataSourceManager;
import com.landawn.abacus.exception.AbacusException;
import com.landawn.abacus.exception.DuplicatedResultException;
import com.landawn.abacus.exception.ParseException;
import com.landawn.abacus.exception.UncheckedIOException;
import com.landawn.abacus.exception.UncheckedSQLException;
import com.landawn.abacus.logging.Logger;
import com.landawn.abacus.logging.LoggerFactory;
import com.landawn.abacus.parser.ParserUtil;
import com.landawn.abacus.parser.ParserUtil.EntityInfo;
import com.landawn.abacus.parser.ParserUtil.PropInfo;
import com.landawn.abacus.type.Type;
import com.landawn.abacus.type.TypeFactory;
import com.landawn.abacus.util.ExceptionalStream.ExceptionalIterator;
import com.landawn.abacus.util.ExceptionalStream.StreamE;
import com.landawn.abacus.util.Fn.BiConsumers;
import com.landawn.abacus.util.Fn.Fnn;
import com.landawn.abacus.util.Fn.IntFunctions;
import com.landawn.abacus.util.Fn.Suppliers;
import com.landawn.abacus.util.SQLBuilder.NAC;
import com.landawn.abacus.util.SQLBuilder.NLC;
import com.landawn.abacus.util.SQLBuilder.NSC;
import com.landawn.abacus.util.SQLBuilder.PAC;
import com.landawn.abacus.util.SQLBuilder.PLC;
import com.landawn.abacus.util.SQLBuilder.PSC;
import com.landawn.abacus.util.SQLBuilder.SP;
import com.landawn.abacus.util.SQLExecutor.StatementSetter;
import com.landawn.abacus.util.SQLTransaction.CreatedBy;
import com.landawn.abacus.util.StringUtil.Strings;
import com.landawn.abacus.util.Try.Consumer;
import com.landawn.abacus.util.Tuple.Tuple2;
import com.landawn.abacus.util.Tuple.Tuple3;
import com.landawn.abacus.util.Tuple.Tuple4;
import com.landawn.abacus.util.Tuple.Tuple5;
import com.landawn.abacus.util.u.Nullable;
import com.landawn.abacus.util.u.Optional;
import com.landawn.abacus.util.u.OptionalBoolean;
import com.landawn.abacus.util.u.OptionalByte;
import com.landawn.abacus.util.u.OptionalChar;
import com.landawn.abacus.util.u.OptionalDouble;
import com.landawn.abacus.util.u.OptionalFloat;
import com.landawn.abacus.util.u.OptionalInt;
import com.landawn.abacus.util.u.OptionalLong;
import com.landawn.abacus.util.u.OptionalShort;
import com.landawn.abacus.util.function.BiConsumer;
import com.landawn.abacus.util.function.BiFunction;
import com.landawn.abacus.util.function.Function;
import com.landawn.abacus.util.function.LongFunction;
import com.landawn.abacus.util.function.Predicate;
import com.landawn.abacus.util.function.Supplier;
import com.landawn.abacus.util.stream.Collector;
import com.landawn.abacus.util.stream.EntryStream;
import com.landawn.abacus.util.stream.IntStream.IntStreamEx;
import com.landawn.abacus.util.stream.Stream;
import com.landawn.abacus.util.stream.Stream.StreamEx;

// TODO: Auto-generated Javadoc
/**
 * The Class JdbcUtil.
 *
 * @author Haiyang Li
 * @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
 */
public final class JdbcUtil {

    /** The Constant logger. */
    private static final Logger logger = LoggerFactory.getLogger(JdbcUtil.class);

    /** The Constant DEFAULT_BATCH_SIZE. */
    public static final int DEFAULT_BATCH_SIZE = 200;

    /** The Constant CURRENT_DIR_PATH. */
    // ...
    static final String CURRENT_DIR_PATH = "./";

    /** The async executor. */
    static final AsyncExecutor asyncExecutor = new AsyncExecutor(Math.max(8, IOUtil.CPU_CORES), Math.max(64, IOUtil.CPU_CORES), 180L, TimeUnit.SECONDS);

    /** The Constant DEFAULT_STMT_SETTER. */
    static final JdbcUtil.BiParametersSetter DEFAULT_STMT_SETTER = new JdbcUtil.BiParametersSetter() {
        @Override
        public void accept(PreparedStatement stmt, Object[] parameters) throws SQLException {
            for (int i = 0, len = parameters.length; i < len; i++) {
                stmt.setObject(i + 1, parameters[i]);
            }
        }
    };

    /** The Constant sqlStateForTableNotExists. */
    private static final Set sqlStateForTableNotExists = N.newHashSet();

    static {
        sqlStateForTableNotExists.add("42S02"); // for MySQCF.
        sqlStateForTableNotExists.add("42P01"); // for PostgreSQCF.
        sqlStateForTableNotExists.add("42501"); // for HSQLDB.
    }

    /**
     * Instantiates a new jdbc util.
     */
    private JdbcUtil() {
        // singleton
    }

    /**
     * Gets the DB version.
     *
     * @param conn
     * @return
     * @throws UncheckedSQLException the unchecked SQL exception
     */
    public static DBVersion getDBVersion(final Connection conn) throws UncheckedSQLException {
        try {
            String dbProudctName = conn.getMetaData().getDatabaseProductName();
            String dbProudctVersion = conn.getMetaData().getDatabaseProductVersion();

            DBVersion dbVersion = DBVersion.OTHERS;

            String upperCaseProductName = dbProudctName.toUpperCase();
            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 dbVersion;
        } catch (SQLException e) {
            throw new UncheckedSQLException(e);
        }
    }

    /**
     * Creates the data source manager.
     *
     * @param dataSourceXmlFile
     * @return DataSourceManager
     * @throws UncheckedIOException the unchecked IO exception
     * @throws UncheckedSQLException the unchecked SQL exception
     * @see DataSource.xsd
     */
    public static DataSourceManager createDataSourceManager(final String dataSourceXmlFile) throws UncheckedIOException, UncheckedSQLException {
        InputStream is = null;
        try {
            is = new FileInputStream(Configuration.findFile(dataSourceXmlFile));
            return createDataSourceManager(is, dataSourceXmlFile);
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        } finally {
            IOUtil.close(is);
        }

    }

    /**
     * Creates the data source manager.
     *
     * @param dataSourceXmlInputStream
     * @return DataSourceManager
     * @throws UncheckedIOException the unchecked IO exception
     * @throws UncheckedSQLException the unchecked SQL exception
     * @see DataSource.xsd
     */
    public static DataSourceManager createDataSourceManager(final InputStream dataSourceXmlInputStream) throws UncheckedIOException, UncheckedSQLException {
        return createDataSourceManager(dataSourceXmlInputStream, CURRENT_DIR_PATH);
    }

    /** The Constant PROPERTIES. */
    private static final String PROPERTIES = "properties";

    /** The Constant RESOURCE. */
    private static final String RESOURCE = "resource";

    /**
     * Creates the data source manager.
     *
     * @param dataSourceXmlInputStream
     * @param dataSourceXmlFile
     * @return
     * @throws UncheckedIOException the unchecked IO exception
     * @throws UncheckedSQLException the unchecked SQL exception
     */
    private static DataSourceManager createDataSourceManager(final InputStream dataSourceXmlInputStream, final String dataSourceXmlFile)
            throws UncheckedIOException, UncheckedSQLException {
        DocumentBuilder domParser = XMLUtil.createDOMParser();
        Document doc = null;

        try {
            doc = domParser.parse(dataSourceXmlInputStream);

            Element rootElement = doc.getDocumentElement();

            final Map props = new HashMap<>();
            List propertiesElementList = XMLUtil.getElementsByTagName(rootElement, PROPERTIES);

            if (N.notNullOrEmpty(propertiesElementList)) {
                for (Element propertiesElement : propertiesElementList) {
                    File resourcePropertiesFile = Configuration.findFileByFile(new File(dataSourceXmlFile), propertiesElement.getAttribute(RESOURCE));
                    java.util.Properties properties = new java.util.Properties();
                    InputStream is = null;

                    try {
                        is = new FileInputStream(resourcePropertiesFile);

                        if (resourcePropertiesFile.getName().endsWith(".xml")) {
                            properties.loadFromXML(is);
                        } else {
                            properties.load(is);
                        }
                    } finally {
                        IOUtil.close(is);
                    }

                    for (Object key : properties.keySet()) {
                        props.put((String) key, (String) properties.get(key));
                    }
                }
            }

            String nodeName = rootElement.getNodeName();
            if (nodeName.equals(DataSourceManagerConfiguration.DATA_SOURCE_MANAGER)) {
                DataSourceManagerConfiguration config = new DataSourceManagerConfiguration(rootElement, props);
                return new SQLDataSourceManager(config);
            } else if (nodeName.equals(DataSourceConfiguration.DATA_SOURCE)) {
                DataSourceConfiguration config = new DataSourceConfiguration(rootElement, props);
                return new SimpleDataSourceManager(new SQLDataSource(config));
            } else {
                throw new AbacusException("Unknown xml format with root element: " + nodeName);
            }
        } catch (SAXException e) {
            throw new ParseException(e);
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    /**
     * Creates the data source.
     *
     * @param dataSourceFile
     * @return
     * @throws UncheckedIOException the unchecked IO exception
     * @throws UncheckedSQLException the unchecked SQL exception
     * @see DataSource.xsd
     */
    public static DataSource createDataSource(final String dataSourceFile) throws UncheckedIOException, UncheckedSQLException {
        InputStream is = null;
        try {
            is = new FileInputStream(Configuration.findFile(dataSourceFile));
            return createDataSource(is, dataSourceFile);
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        } finally {
            IOUtil.close(is);
        }
    }

    /**
     * Creates the data source.
     *
     * @param dataSourceInputStream
     * @return
     * @throws UncheckedIOException the unchecked IO exception
     * @throws UncheckedSQLException the unchecked SQL exception
     * @see DataSource.xsd
     */
    public static DataSource createDataSource(final InputStream dataSourceInputStream) throws UncheckedIOException, UncheckedSQLException {
        return createDataSource(dataSourceInputStream, CURRENT_DIR_PATH);
    }

    /**
     * Creates the data source.
     *
     * @param dataSourceInputStream
     * @param dataSourceFile
     * @return
     * @throws UncheckedIOException the unchecked IO exception
     * @throws UncheckedSQLException the unchecked SQL exception
     */
    private static DataSource createDataSource(final InputStream dataSourceInputStream, final String dataSourceFile)
            throws UncheckedIOException, UncheckedSQLException {
        final String dataSourceString = IOUtil.readString(dataSourceInputStream);

        if (CURRENT_DIR_PATH.equals(dataSourceFile) || dataSourceFile.endsWith(".xml")) {
            try {
                return createDataSourceManager(new ByteArrayInputStream(dataSourceString.getBytes())).getPrimaryDataSource();
            } catch (ParseException e) {
                // ignore.
            } catch (UncheckedIOException e) {
                // ignore.
            }
        }

        final Map newProps = new HashMap<>();
        final java.util.Properties properties = new java.util.Properties();

        try {
            properties.load(new ByteArrayInputStream(dataSourceString.getBytes()));

            Object value = null;

            for (Object key : properties.keySet()) {
                value = properties.get(key);
                newProps.put(key.toString().trim(), value.toString().trim());
            }

        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }

        return new SQLDataSource(newProps);
    }

    /**
     * Creates the data source.
     *
     * @param url
     * @param user
     * @param password
     * @return
     * @throws UncheckedSQLException the unchecked SQL exception
     */
    public static DataSource createDataSource(final String url, final String user, final String password) throws UncheckedSQLException {
        return createDataSource(getDriverClasssByUrl(url), url, user, password);
    }

    /**
     * Creates the data source.
     *
     * @param driver
     * @param url
     * @param user
     * @param password
     * @return
     * @throws UncheckedSQLException the unchecked SQL exception
     */
    public static DataSource createDataSource(final String driver, final String url, final String user, final String password) throws UncheckedSQLException {
        final Class driverClass = ClassUtil.forClass(driver);

        return createDataSource(driverClass, url, user, password);
    }

    /**
     * Creates the data source.
     *
     * @param driverClass
     * @param url
     * @param user
     * @param password
     * @return
     * @throws UncheckedSQLException the unchecked SQL exception
     */
    public static DataSource createDataSource(final Class driverClass, final String url, final String user, final String password)
            throws UncheckedSQLException {
        N.checkArgNotNullOrEmpty(url, "url");

        final Map props = new HashMap<>();

        props.put(DRIVER, driverClass.getCanonicalName());
        props.put(URL, url);
        props.put(USER, user);
        props.put(PASSWORD, password);

        return createDataSource(props);
    }

    /**
     * Creates the data source.
     *
     * @param props refer to Connection.xsd for the supported properties.
     * @return
     * @throws UncheckedSQLException the unchecked SQL exception
     */
    public static DataSource createDataSource(final Map props) throws UncheckedSQLException {
        final String driver = (String) props.get(DRIVER);

        if (N.isNullOrEmpty(driver)) {
            final String url = (String) props.get(URL);

            if (N.isNullOrEmpty(url)) {
                throw new IllegalArgumentException("Url is not specified");
            }

            final Map tmp = new HashMap<>(props);

            tmp.put(DRIVER, getDriverClasssByUrl(url).getCanonicalName());

            return new SQLDataSource(tmp);
        } else {
            return new SQLDataSource(props);
        }
    }

    //    /**
    //     *
    //     * @param sqlDataSource
    //     * @return
    //     * @deprecated
    //     */
    //    @Deprecated
    //    public static DataSource wrap(final javax.sql.DataSource sqlDataSource) {
    //        return sqlDataSource instanceof DataSource ? ((DataSource) sqlDataSource) : new SimpleDataSource(sqlDataSource);
    //    }

    /**
     * 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);
    }

    /**
     * Gets the driver classs by url.
     *
     * @param url
     * @return
     */
    private static Class getDriverClasssByUrl(final String url) {
        N.checkArgNotNullOrEmpty(url, "url");

        Class driverClass = null;
        // jdbc:mysql://localhost:3306/abacustest
        if (url.indexOf("mysql") > 0 || StringUtil.indexOfIgnoreCase(url, "mysql") > 0) {
            driverClass = ClassUtil.forClass("com.mysql.jdbc.Driver");
            // jdbc:postgresql://localhost:5432/abacustest
        } else if (url.indexOf("postgresql") > 0 || StringUtil.indexOfIgnoreCase(url, "postgresql") > 0) {
            driverClass = ClassUtil.forClass("org.postgresql.Driver");
            // jdbc:h2:hsql://:/
        } else if (url.indexOf("h2") > 0 || StringUtil.indexOfIgnoreCase(url, "h2") > 0) {
            driverClass = ClassUtil.forClass("org.h2.Driver");
            // jdbc:hsqldb:hsql://localhost/abacustest
        } else if (url.indexOf("hsqldb") > 0 || StringUtil.indexOfIgnoreCase(url, "hsqldb") > 0) {
            driverClass = ClassUtil.forClass("org.hsqldb.jdbc.JDBCDriver");
            // jdbc.url=jdbc:oracle:thin:@localhost:1521:abacustest
        } else if (url.indexOf("oracle") > 0 || StringUtil.indexOfIgnoreCase(url, "oracle") > 0) {
            driverClass = ClassUtil.forClass("oracle.jdbc.driver.OracleDriver");
            // jdbc.url=jdbc:sqlserver://localhost:1433;Database=abacustest
        } else if (url.indexOf("sqlserver") > 0 || StringUtil.indexOfIgnoreCase(url, "sqlserver") > 0) {
            driverClass = ClassUtil.forClass("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            // jdbc:db2://localhost:50000/abacustest
        } else if (url.indexOf("db2") > 0 || StringUtil.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;
    }

    /**
     * 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 {
        Class 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 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);
        }
    }

    /** The is in spring. */
    private static boolean isInSpring = true;

    static {
        try {
            isInSpring = ClassUtil.forClass("org.springframework.jdbc.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) {
            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) {
            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 == false) {
            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 || closeConnection) {
                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 {
                if (stmt instanceof PreparedStatement) {
                    try {
                        ((PreparedStatement) stmt).clearParameters();
                    } catch (SQLException e) {
                        logger.error("Failed to clear parameters", e);
                    }
                }

                stmt.close();
            } catch (SQLException e) {
                throw new UncheckedSQLException(e);
            }
        }
    }

    /**
     *
     * @param conn
     * @throws UncheckedSQLException the unchecked SQL exception
     */
    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) {
                    if (stmt instanceof PreparedStatement) {
                        try {
                            ((PreparedStatement) stmt).clearParameters();
                        } catch (SQLException e) {
                            logger.error("Failed to clear parameters", e);
                        }
                    }
                    stmt.close();
                }
            } catch (SQLException e) {
                throw new UncheckedSQLException(e);
            }
        }
    }

    /**
     *
     * @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) {
                if (stmt instanceof PreparedStatement) {
                    try {
                        ((PreparedStatement) stmt).clearParameters();
                    } catch (SQLException e) {
                        logger.error("Failed to clear parameters", e);
                    }
                }
                stmt.close();
            }
        } catch (SQLException e) {
            throw new UncheckedSQLException(e);
        } finally {
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                throw new UncheckedSQLException(e);
            }
        }
    }

    /**
     *
     * @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) {
                    if (stmt instanceof PreparedStatement) {
                        try {
                            ((PreparedStatement) stmt).clearParameters();
                        } catch (SQLException e) {
                            logger.error("Failed to clear parameters", e);
                        }
                    }
                    stmt.close();
                }
            } catch (SQLException e) {
                throw new UncheckedSQLException(e);
            } finally {
                try {
                    if (conn != null) {
                        conn.close();
                    }
                } catch (SQLException e) {
                    throw new UncheckedSQLException(e);
                }
            }
        }
    }

    /**
     * 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 == false) { 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 || closeConnection) { 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 */ 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) { if (stmt instanceof PreparedStatement) { try { ((PreparedStatement) stmt).clearParameters(); } catch (Exception e) { logger.error("Failed to clear parameters", e); } } 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 the SQL exception */ public static int skip(final ResultSet rs, int n) throws SQLException { return skip(rs, (long) n); } /** * * @param rs * @param n the count of row to move ahead. * @return * @throws SQLException the SQL exception * @see {@link ResultSet#absolute(int)} */ public static int skip(final ResultSet rs, long n) throws SQLException { return InternalJdbcUtil.skip(rs, n); } /** * Gets the column count. * * @param rs * @return * @throws SQLException the SQL exception */ public static int getColumnCount(ResultSet rs) throws SQLException { return rs.getMetaData().getColumnCount(); } /** * Gets the column name list. * * @param conn * @param tableName * @return * @throws SQLException the SQL exception */ 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 = stmt.executeQuery(); 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); } } /** * Gets the column label list. * * @param rs * @return * @throws SQLException the SQL exception */ public static List getColumnLabelList(ResultSet rs) throws SQLException { return InternalJdbcUtil.getColumnLabelList(rs); } /** * Gets the column label. * * @param rsmd * @param columnIndex * @return * @throws SQLException the SQL exception */ public static String getColumnLabel(final ResultSetMetaData rsmd, final int columnIndex) throws SQLException { return InternalJdbcUtil.getColumnLabel(rsmd, columnIndex); } /** * Gets the column value. * * @param rs * @param columnIndex * @return * @throws SQLException the SQL exception */ public static Object getColumnValue(final ResultSet rs, final int columnIndex) throws SQLException { return InternalJdbcUtil.getColumnValue(rs, columnIndex); } /** * Gets the column value. * * @param rs * @param columnLabel * @return * @throws SQLException the SQL exception */ public static Object getColumnValue(final ResultSet rs, final String columnLabel) throws SQLException { return InternalJdbcUtil.getColumnValue(rs, columnLabel); } /** * Gets the column value. * * @param * @param targetClass * @param rs * @param columnIndex * @return * @throws SQLException the SQL exception */ public static T getColumnValue(final Class targetClass, final ResultSet rs, final int columnIndex) throws SQLException { return N. typeOf(targetClass).get(rs, columnIndex); } /** * Gets the column value. * * @param * @param targetClass * @param rs * @param columnLabel * @return * @throws SQLException the SQL exception */ public static T getColumnValue(final Class targetClass, final ResultSet rs, final String columnLabel) throws SQLException { return N. typeOf(targetClass).get(rs, columnLabel); } /** * Refer to: {@code beginTransaction(javax.sql.DataSource, IsolationLevel, boolean)}. * * @param dataSource * @return * @throws UncheckedSQLException the unchecked SQL exception * @see {@link #beginTransaction(javax.sql.DataSource, IsolationLevel, boolean)} */ public static SQLTransaction beginTransaction(final javax.sql.DataSource dataSource) throws UncheckedSQLException { return beginTransaction(dataSource, IsolationLevel.DEFAULT); } /** * Refer to: {@code beginTransaction(javax.sql.DataSource, IsolationLevel, boolean)}. * * @param dataSource * @param isolationLevel * @return * @throws UncheckedSQLException the unchecked SQL exception * @see {@link #beginTransaction(javax.sql.DataSource, IsolationLevel, boolean)} */ public static SQLTransaction beginTransaction(final javax.sql.DataSource dataSource, final IsolationLevel isolationLevel) throws UncheckedSQLException { return beginTransaction(dataSource, isolationLevel, false); } /** * Starts a global transaction which will be shared by all in-line database query with the same {@code DataSource} in the same thread, * including methods: {@code JdbcUtil.beginTransaction/prepareQuery/prepareNamedQuery/prepareCallableQuery, SQLExecutor(Mapper).beginTransaction/get/insert/batchInsert/update/batchUpdate/query/list/findFirst/...} * *
* Spring Transaction is supported and Integrated. * If this method is called at where a Spring transaction is started with the specified {@code DataSource}, * the {@code Connection} started the Spring Transaction will be used here. * That's to say the Spring transaction will have the final control on commit/roll back over the {@code Connection}. * *
*
* * Here is the general code pattern to work with {@code SQLTransaction}. * *

     * 
     * public void doSomethingA() {
     *     ...
     *     final SQLTransaction tranA = JdbcUtil.beginTransaction(dataSource1, isolation);
     *
     *     try {
     *         ...
     *         doSomethingB(); // Share the same transaction 'tranA' because they're in the same thread and start transaction with same DataSource 'dataSource1'.
     *         ...
     *         doSomethingC(); // won't share the same transaction 'tranA' although they're in the same thread but start transaction with different DataSource 'dataSource2'.
     *         ...
     *         tranA.commit();
     *     } finally {
     *         tranA.rollbackIfNotCommitted();
     *     }
     * }
     *
     * public void doSomethingB() {
     *     ...
     *     final SQLTransaction tranB = JdbcUtil.beginTransaction(dataSource1, isolation);
     *     try {
     *         // do your work with the conn...
     *         ...
     *         tranB.commit();
     *     } finally {
     *         tranB.rollbackIfNotCommitted();
     *     }
     * }
     *
     * public void doSomethingC() {
     *     ...
     *     final SQLTransaction tranC = JdbcUtil.beginTransaction(dataSource2, isolation);
     *     try {
     *         // do your work with the conn...
     *         ...
     *         tranC.commit();
     *     } finally {
     *         tranC.rollbackIfNotCommitted();
     *     }
     * }
     * 
* * * 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 { conn = getConnection(dataSource); tran = new SQLTransaction(dataSource, conn, isolationLevel, CreatedBy.JDBC_UTIL, true); tran.incrementAndGetRef(isolationLevel, isForUpdateOnly); noException = true; } catch (SQLException e) { throw new UncheckedSQLException(e); } finally { if (noException == false) { 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 ds * @param callable * @return * @throws E */ @Beta public static T doInTransaction(final javax.sql.DataSource ds, final Try.Callable callable) throws E { final SQLTransaction tran = JdbcUtil.beginTransaction(ds); T result = null; try { result = callable.call(); tran.commit(); } finally { tran.rollbackIfNotCommitted(); } return result; } /** * * @param * @param * @param ds * @param func * @return * @throws E */ @Beta public static T doInTransaction(final javax.sql.DataSource ds, final Try.Function func) throws E { final SQLTransaction tran = JdbcUtil.beginTransaction(ds); T result = null; try { result = func.apply(ds); tran.commit(); } finally { tran.rollbackIfNotCommitted(); } return result; } /** * * @param * @param ds * @param runnable * @return * @throws E */ @Beta public static void runInTransaction(final javax.sql.DataSource ds, final Try.Runnable runnable) throws E { final SQLTransaction tran = JdbcUtil.beginTransaction(ds); try { runnable.run(); tran.commit(); } finally { tran.rollbackIfNotCommitted(); } } /** * * @param * @param ds * @param action * @return * @throws E */ @Beta public static void runInTransaction(final javax.sql.DataSource ds, final Try.Consumer action) throws E { final SQLTransaction tran = JdbcUtil.beginTransaction(ds); try { action.accept(ds); tran.commit(); } finally { tran.rollbackIfNotCommitted(); } } /** * Gets the SQL operation. * * @param sql * @return */ static SQLOperation getSQLOperation(String sql) { if (StringUtil.startsWithIgnoreCase(sql.trim(), "select ")) { return SQLOperation.SELECT; } else if (StringUtil.startsWithIgnoreCase(sql.trim(), "update ")) { return SQLOperation.UPDATE; } else if (StringUtil.startsWithIgnoreCase(sql.trim(), "insert ")) { return SQLOperation.INSERT; } else if (StringUtil.startsWithIgnoreCase(sql.trim(), "delete ")) { return SQLOperation.DELETE; } else { for (SQLOperation so : SQLOperation.values()) { if (StringUtil.startsWithIgnoreCase(sql.trim(), so.name())) { return so; } } } throw new IllegalArgumentException("Unsupported sql operation: " + sql.substring(0, sql.indexOf(' '))); } /** * 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 SQLException the SQL exception * @see #getConnection(javax.sql.DataSource) * @see #releaseConnection(Connection, javax.sql.DataSource) */ public static PreparedQuery prepareQuery(final javax.sql.DataSource ds, final String sql) throws SQLException { 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 SQLException the SQL exception * @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 SQLException { 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 SQLException the SQL exception */ public static PreparedQuery prepareQuery(final javax.sql.DataSource ds, final String sql, final int[] returnColumnIndexes) throws SQLException { 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 SQLException the SQL exception */ public static PreparedQuery prepareQuery(final javax.sql.DataSource ds, final String sql, final String[] returnColumnNames) throws SQLException { 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/PreparedCallableQuery} 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/list/execute/.... * @return * @throws SQLException the SQL exception * @see #getConnection(javax.sql.DataSource) * @see #releaseConnection(Connection, javax.sql.DataSource) */ public static PreparedQuery prepareQuery(final javax.sql.DataSource ds, final String sql, final Try.BiFunction stmtCreator) throws SQLException { 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: *
     * 
     * JdbcUtil.prepareQuery(dataSource.getConnection(), sql);
     * 
     * 
* * @param conn the specified {@code conn} won't be close after this query is executed. * @param sql * @return * @throws SQLException the SQL exception */ public static PreparedQuery prepareQuery(final Connection conn, final String sql) throws SQLException { N.checkArgNotNull(conn, "conn"); N.checkArgNotNull(sql, "sql"); return new PreparedQuery(conn.prepareStatement(sql)); } /** * * Never write below code because it will definitely cause {@code Connection} leak: *
     * 
     * JdbcUtil.prepareQuery(dataSource.getConnection(), sql, autoGeneratedKeys);
     * 
     * 
* * @param conn the specified {@code conn} won't be close after this query is executed. * @param sql * @param autoGeneratedKeys * @return * @throws SQLException the SQL exception */ public static PreparedQuery prepareQuery(final Connection conn, final String sql, final boolean autoGeneratedKeys) throws SQLException { N.checkArgNotNull(conn, "conn"); N.checkArgNotNull(sql, "sql"); return new PreparedQuery(conn.prepareStatement(sql, autoGeneratedKeys ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS)); } /** * Never write below code because it will definitely cause {@code Connection} leak: *
     * 
     * JdbcUtil.prepareQuery(dataSource.getConnection(), sql, returnColumnIndexes);
     * 
     * 
* * @param conn * @param sql * @param returnColumnIndexes * @return * @throws SQLException the SQL exception */ public static PreparedQuery prepareQuery(final Connection conn, final String sql, final int[] returnColumnIndexes) throws SQLException { N.checkArgNotNull(conn, "conn"); N.checkArgNotNull(sql, "sql"); N.checkArgNotNullOrEmpty(returnColumnIndexes, "returnColumnIndexes"); return new PreparedQuery(conn.prepareStatement(sql, returnColumnIndexes)); } /** * Never write below code because it will definitely cause {@code Connection} leak: *
     * 
     * JdbcUtil.prepareQuery(dataSource.getConnection(), sql, returnColumnNames);
     * 
     * 
* * @param conn * @param sql * @param returnColumnNames * @return * @throws SQLException the SQL exception */ public static PreparedQuery prepareQuery(final Connection conn, final String sql, final String[] returnColumnNames) throws SQLException { N.checkArgNotNull(conn, "conn"); N.checkArgNotNull(sql, "sql"); N.checkArgNotNullOrEmpty(returnColumnNames, "returnColumnNames"); return new PreparedQuery(conn.prepareStatement(sql, returnColumnNames)); } /** * Never write below code because it will definitely cause {@code Connection} leak: *
     * 
     * JdbcUtil.prepareQuery(dataSource.getConnection(), sql, stmtCreator);
     * 
     * 
* * @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/PreparedCallableQuery} 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/list/execute/.... * @return * @throws SQLException the SQL exception * @see {@link JdbcUtil#prepareStatement(Connection, String, Object...)} */ public static PreparedQuery prepareQuery(final Connection conn, final String sql, final Try.BiFunction stmtCreator) throws SQLException { N.checkArgNotNull(conn, "conn"); N.checkArgNotNull(sql, "sql"); N.checkArgNotNull(stmtCreator, "stmtCreator"); return new PreparedQuery(stmtCreator.apply(conn, sql)); } /** * 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 SQLException the SQL exception * @see #getConnection(javax.sql.DataSource) * @see #releaseConnection(Connection, javax.sql.DataSource) */ public static NamedQuery prepareNamedQuery(final javax.sql.DataSource ds, final String namedSql) throws SQLException { 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 SQLException the SQL exception * @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 SQLException { 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 SQLException the SQL exception */ public static NamedQuery prepareNamedQuery(final javax.sql.DataSource ds, final String namedSql, final int[] returnColumnIndexes) throws SQLException { 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 SQLException the SQL exception */ public static NamedQuery prepareNamedQuery(final javax.sql.DataSource ds, final String namedSql, final String[] returnColumnNames) throws SQLException { 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/PreparedCallableQuery} 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/list/execute/.... * @return * @throws SQLException the SQL exception * @see #getConnection(javax.sql.DataSource) * @see #releaseConnection(Connection, javax.sql.DataSource) */ public static NamedQuery prepareNamedQuery(final javax.sql.DataSource ds, final String namedSql, final Try.BiFunction stmtCreator) throws SQLException { 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: *
     * 
     * JdbcUtil.prepareNamedQuery(dataSource.getConnection(), namedSql);
     * 
     * 
* * @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 SQLException the SQL exception */ public static NamedQuery prepareNamedQuery(final Connection conn, final String namedSql) throws SQLException { N.checkArgNotNull(conn, "conn"); N.checkArgNotNull(namedSql, "namedSql"); final NamedSQL namedSQL = createNamedSQL(namedSql); return new NamedQuery(conn.prepareStatement(namedSQL.getParameterizedSQL()), namedSQL); } /** * * Never write below code because it will definitely cause {@code Connection} leak: *
     * 
     * JdbcUtil.prepareNamedQuery(dataSource.getConnection(), namedSql, autoGeneratedKeys);
     * 
     * 
* * @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 SQLException the SQL exception */ public static NamedQuery prepareNamedQuery(final Connection conn, final String namedSql, final boolean autoGeneratedKeys) throws SQLException { N.checkArgNotNull(conn, "conn"); N.checkArgNotNull(namedSql, "namedSql"); final NamedSQL namedSQL = createNamedSQL(namedSql); return new NamedQuery( conn.prepareStatement(namedSQL.getParameterizedSQL(), autoGeneratedKeys ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS), namedSQL); } /** * Never write below code because it will definitely cause {@code Connection} leak: *
     * 
     * JdbcUtil.prepareNamedQuery(dataSource.getConnection(), namedSql);
     * 
     * 
* * @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 SQLException the SQL exception */ public static NamedQuery prepareNamedQuery(final Connection conn, final String namedSql, final int[] returnColumnIndexes) throws SQLException { N.checkArgNotNull(conn, "conn"); N.checkArgNotNull(namedSql, "namedSql"); N.checkArgNotNullOrEmpty(returnColumnIndexes, "returnColumnIndexes"); final NamedSQL namedSQL = createNamedSQL(namedSql); return new NamedQuery(conn.prepareStatement(namedSQL.getParameterizedSQL(), returnColumnIndexes), namedSQL); } /** * Never write below code because it will definitely cause {@code Connection} leak: *
     * 
     * JdbcUtil.prepareNamedQuery(dataSource.getConnection(), namedSql);
     * 
     * 
* * @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 SQLException the SQL exception */ public static NamedQuery prepareNamedQuery(final Connection conn, final String namedSql, final String[] returnColumnNames) throws SQLException { N.checkArgNotNull(conn, "conn"); N.checkArgNotNull(namedSql, "namedSql"); N.checkArgNotNullOrEmpty(returnColumnNames, "returnColumnNames"); final NamedSQL namedSQL = createNamedSQL(namedSql); return new NamedQuery(conn.prepareStatement(namedSQL.getParameterizedSQL(), returnColumnNames), namedSQL); } /** * Never write below code because it will definitely cause {@code Connection} leak: *
     * 
     * JdbcUtil.prepareNamedQuery(dataSource.getConnection(), namedSql, stmtCreator);
     * 
     * 
* * @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/PreparedCallableQuery} 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/list/execute/.... * @return * @throws SQLException the SQL exception * @see {@link JdbcUtil#prepareStatement(Connection, String, Object...)} */ public static NamedQuery prepareNamedQuery(final Connection conn, final String namedSql, final Try.BiFunction stmtCreator) throws SQLException { N.checkArgNotNull(conn, "conn"); N.checkArgNotNull(namedSql, "namedSql"); N.checkArgNotNull(stmtCreator, "stmtCreator"); final NamedSQL namedSQL = createNamedSQL(namedSql); return new NamedQuery(stmtCreator.apply(conn, namedSQL.getParameterizedSQL()), namedSQL); } /** * Creates the named SQL. * * @param namedSql * @return */ private static NamedSQL createNamedSQL(final String namedSql) { N.checkArgNotNullOrEmpty(namedSql, "namedSql"); final NamedSQL namedSQL = NamedSQL.parse(namedSql); validateNamedSQL(namedSQL); return namedSQL; } private static void validateNamedSQL(final NamedSQL namedSQL) { if (namedSQL.getNamedParameters().size() != namedSQL.getParameterCount()) { throw new IllegalArgumentException("\"" + namedSQL.getNamedSQL() + "\" is not a valid named sql:"); } } private static SQLTransaction getTransaction(final javax.sql.DataSource ds, final String sql, final CreatedBy createdBy) { final SQLOperation sqlOperation = JdbcUtil.getSQLOperation(sql); final SQLTransaction tran = SQLTransaction.getTransaction(ds, createdBy); if (tran == null || (tran.isForUpdateOnly() && sqlOperation == SQLOperation.SELECT)) { return null; } else { return tran; } } /** * 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 SQLException the SQL exception * @see #getConnection(javax.sql.DataSource) * @see #releaseConnection(Connection, javax.sql.DataSource) */ public static NamedQuery prepareNamedQuery(final javax.sql.DataSource ds, final NamedSQL namedSQL) throws SQLException { 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 SQLException the SQL exception * @see #getConnection(javax.sql.DataSource) * @see #releaseConnection(Connection, javax.sql.DataSource) */ public static NamedQuery prepareNamedQuery(final javax.sql.DataSource ds, final NamedSQL namedSQL, final boolean autoGeneratedKeys) throws SQLException { 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 SQLException the SQL exception */ public static NamedQuery prepareNamedQuery(final javax.sql.DataSource ds, final NamedSQL namedSQL, final int[] returnColumnIndexes) throws SQLException { 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 SQLException the SQL exception */ public static NamedQuery prepareNamedQuery(final javax.sql.DataSource ds, final NamedSQL namedSQL, final String[] returnColumnNames) throws SQLException { 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/PreparedCallableQuery} 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/list/execute/.... * @return * @throws SQLException the SQL exception * @see #getConnection(javax.sql.DataSource) * @see #releaseConnection(Connection, javax.sql.DataSource) */ public static NamedQuery prepareNamedQuery(final javax.sql.DataSource ds, final NamedSQL namedSQL, final Try.BiFunction stmtCreator) throws SQLException { 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: *
     * 
     * JdbcUtil.prepareNamedQuery(dataSource.getConnection(), namedSQL);
     * 
     * 
* * @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 SQLException the SQL exception */ public static NamedQuery prepareNamedQuery(final Connection conn, final NamedSQL namedSQL) throws SQLException { N.checkArgNotNull(conn, "conn"); N.checkArgNotNull(namedSQL, "namedSQL"); validateNamedSQL(namedSQL); return new NamedQuery(conn.prepareStatement(namedSQL.getParameterizedSQL()), namedSQL); } /** * * Never write below code because it will definitely cause {@code Connection} leak: *
     * 
     * JdbcUtil.prepareNamedQuery(dataSource.getConnection(), namedSQL, autoGeneratedKeys);
     * 
     * 
* * @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 SQLException the SQL exception */ public static NamedQuery prepareNamedQuery(final Connection conn, final NamedSQL namedSQL, final boolean autoGeneratedKeys) throws SQLException { N.checkArgNotNull(conn, "conn"); N.checkArgNotNull(namedSQL, "namedSQL"); validateNamedSQL(namedSQL); return new NamedQuery( conn.prepareStatement(namedSQL.getParameterizedSQL(), autoGeneratedKeys ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS), namedSQL); } /** * Never write below code because it will definitely cause {@code Connection} leak: *
     * 
     * JdbcUtil.prepareNamedQuery(dataSource.getConnection(), namedSQL);
     * 
     * 
* * @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 SQLException the SQL exception */ public static NamedQuery prepareNamedQuery(final Connection conn, final NamedSQL namedSQL, final int[] returnColumnIndexes) throws SQLException { N.checkArgNotNull(conn, "conn"); N.checkArgNotNull(namedSQL, "namedSQL"); N.checkArgNotNullOrEmpty(returnColumnIndexes, "returnColumnIndexes"); validateNamedSQL(namedSQL); return new NamedQuery(conn.prepareStatement(namedSQL.getParameterizedSQL(), returnColumnIndexes), namedSQL); } /** * Never write below code because it will definitely cause {@code Connection} leak: *
     * 
     * JdbcUtil.prepareNamedQuery(dataSource.getConnection(), namedSQL);
     * 
     * 
* * @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 SQLException the SQL exception */ public static NamedQuery prepareNamedQuery(final Connection conn, final NamedSQL namedSQL, final String[] returnColumnNames) throws SQLException { N.checkArgNotNull(conn, "conn"); N.checkArgNotNull(namedSQL, "namedSQL"); N.checkArgNotNullOrEmpty(returnColumnNames, "returnColumnNames"); validateNamedSQL(namedSQL); return new NamedQuery(conn.prepareStatement(namedSQL.getParameterizedSQL(), returnColumnNames), namedSQL); } /** * Never write below code because it will definitely cause {@code Connection} leak: *
     * 
     * JdbcUtil.prepareNamedQuery(dataSource.getConnection(), namedSQL, stmtCreator);
     * 
     * 
* * @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/PreparedCallableQuery} 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/list/execute/.... * @return * @throws SQLException the SQL exception * @see {@link JdbcUtil#prepareStatement(Connection, String, Object...)} */ public static NamedQuery prepareNamedQuery(final Connection conn, final NamedSQL namedSQL, final Try.BiFunction stmtCreator) throws SQLException { N.checkArgNotNull(conn, "conn"); N.checkArgNotNull(namedSQL, "namedSQL"); N.checkArgNotNull(stmtCreator, "stmtCreator"); validateNamedSQL(namedSQL); return new NamedQuery(stmtCreator.apply(conn, namedSQL.getParameterizedSQL()), namedSQL); } /** * 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 SQLException the SQL exception * @see #getConnection(javax.sql.DataSource) * @see #releaseConnection(Connection, javax.sql.DataSource) */ public static PreparedCallableQuery prepareCallableQuery(final javax.sql.DataSource ds, final String sql) throws SQLException { final SQLTransaction tran = getTransaction(ds, sql, CreatedBy.JDBC_UTIL); if (tran != null) { return prepareCallableQuery(tran.connection(), sql); } else { PreparedCallableQuery 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/PreparedCallableQuery} 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/list/execute/.... * @return * @throws SQLException the SQL exception * @see #getConnection(javax.sql.DataSource) * @see #releaseConnection(Connection, javax.sql.DataSource) */ public static PreparedCallableQuery prepareCallableQuery(final javax.sql.DataSource ds, final String sql, final Try.BiFunction stmtCreator) throws SQLException { final SQLTransaction tran = getTransaction(ds, sql, CreatedBy.JDBC_UTIL); if (tran != null) { return prepareCallableQuery(tran.connection(), sql, stmtCreator); } else { PreparedCallableQuery 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: *
     * 
     * JdbcUtil.prepareCallableQuery(dataSource.getConnection(), sql);
     * 
     * 
* * @param conn the specified {@code conn} won't be close after this query is executed. * @param sql * @return * @throws SQLException the SQL exception * @see #getConnection(javax.sql.DataSource) * @see #releaseConnection(Connection, javax.sql.DataSource) */ public static PreparedCallableQuery prepareCallableQuery(final Connection conn, final String sql) throws SQLException { N.checkArgNotNull(conn, "conn"); N.checkArgNotNull(sql, "sql"); return new PreparedCallableQuery(conn.prepareCall(sql)); } /** * Never write below code because it will definitely cause {@code Connection} leak: *
     * 
     * JdbcUtil.prepareCallableQuery(dataSource.getConnection(), sql, stmtCreator);
     * 
     * 
* * @param conn the specified {@code conn} won't be close after this query is executed. * @param sql * @param stmtCreator the created {@code CallableStatement} will be closed after any execution methods in {@code PreparedQuery/PreparedCallableQuery} 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/list/execute/.... * @return * @throws SQLException the SQL exception * @see {@link JdbcUtil#prepareCall(Connection, String, Object...)} */ public static PreparedCallableQuery prepareCallableQuery(final Connection conn, final String sql, final Try.BiFunction stmtCreator) throws SQLException { N.checkArgNotNull(conn, "conn"); N.checkArgNotNull(sql, "sql"); N.checkArgNotNull(stmtCreator, "stmtCreator"); return new PreparedCallableQuery(stmtCreator.apply(conn, sql)); } /** * * @param conn * @param sql * @param parameters * @return * @throws SQLException the SQL exception */ @SafeVarargs static PreparedStatement prepareStatement(final Connection conn, final String sql, final Object... parameters) throws SQLException { N.checkArgNotNull(conn, "conn"); N.checkArgNotNull(sql, "sql"); final NamedSQL namedSQL = NamedSQL.parse(sql); final PreparedStatement stmt = conn.prepareStatement(namedSQL.getParameterizedSQL()); if (N.notNullOrEmpty(parameters)) { StatementSetter.DEFAULT.setParameters(namedSQL, stmt, parameters); } return stmt; } /** * * @param conn * @param sql * @param parameters * @return * @throws SQLException the SQL exception */ @SafeVarargs static CallableStatement prepareCall(final Connection conn, final String sql, final Object... parameters) throws SQLException { N.checkArgNotNull(conn, "conn"); N.checkArgNotNull(sql, "sql"); final NamedSQL namedSQL = NamedSQL.parse(sql); final CallableStatement stmt = conn.prepareCall(namedSQL.getParameterizedSQL()); if (N.notNullOrEmpty(parameters)) { StatementSetter.DEFAULT.setParameters(namedSQL, stmt, parameters); } return stmt; } /** * Batch prepare statement. * * @param conn * @param sql * @param parametersList * @return * @throws SQLException the SQL exception */ static PreparedStatement prepareBatchStatement(final Connection conn, final String sql, final List parametersList) throws SQLException { N.checkArgNotNull(conn, "conn"); N.checkArgNotNull(sql, "sql"); final NamedSQL namedSQL = NamedSQL.parse(sql); final PreparedStatement stmt = conn.prepareStatement(namedSQL.getParameterizedSQL()); for (Object parameters : parametersList) { StatementSetter.DEFAULT.setParameters(namedSQL, stmt, N.asArray(parameters)); stmt.addBatch(); } return stmt; } /** * * @param conn * @param sql * @param parametersList * @return * @throws SQLException the SQL exception */ static CallableStatement prepareBatchCall(final Connection conn, final String sql, final List parametersList) throws SQLException { N.checkArgNotNull(conn, "conn"); N.checkArgNotNull(sql, "sql"); final NamedSQL namedSQL = NamedSQL.parse(sql); final CallableStatement stmt = conn.prepareCall(namedSQL.getParameterizedSQL()); for (Object parameters : parametersList) { StatementSetter.DEFAULT.setParameters(namedSQL, stmt, N.asArray(parameters)); stmt.addBatch(); } return stmt; } /** * * @param ds * @param sql * @param parameters * @return * @throws SQLException the SQL exception */ @SafeVarargs public static DataSet executeQuery(final DataSource ds, final String sql, final Object... parameters) throws SQLException { N.checkArgNotNull(ds, "ds"); N.checkArgNotNull(sql, "sql"); final SQLTransaction tran = getTransaction(ds, sql, CreatedBy.JDBC_UTIL); if (tran != null) { return executeQuery(tran.connection(), sql, parameters); } else { final Connection conn = getConnection(ds); try { return executeQuery(conn, sql, parameters); } finally { JdbcUtil.closeQuietly(conn); } } } /** * * @param conn * @param sql * @param parameters * @return * @throws SQLException the SQL exception */ @SafeVarargs public static DataSet executeQuery(final Connection conn, final String sql, final Object... parameters) throws SQLException { N.checkArgNotNull(conn, "conn"); N.checkArgNotNull(sql, "sql"); PreparedStatement stmt = null; ResultSet rs = null; try { stmt = prepareStatement(conn, sql, parameters); stmt.setFetchDirection(ResultSet.FETCH_FORWARD); rs = stmt.executeQuery(); return extractData(rs); } finally { closeQuietly(rs, stmt); } } /** * * @param stmt * @return * @throws SQLException the SQL exception */ public static DataSet executeQuery(final PreparedStatement stmt) throws SQLException { ResultSet rs = null; try { rs = stmt.executeQuery(); return extractData(rs); } finally { closeQuietly(rs); } } /** * * @param ds * @param sql * @param parameters * @return * @throws SQLException the SQL exception */ @SafeVarargs public static int executeUpdate(final DataSource ds, final String sql, final Object... parameters) throws SQLException { N.checkArgNotNull(ds, "ds"); N.checkArgNotNull(sql, "sql"); final SQLTransaction tran = getTransaction(ds, sql, CreatedBy.JDBC_UTIL); if (tran != null) { return executeUpdate(tran.connection(), sql, parameters); } else { final Connection conn = getConnection(ds); try { return executeUpdate(conn, sql, parameters); } finally { JdbcUtil.closeQuietly(conn); } } } /** * * @param conn * @param sql * @param parameters * @return * @throws SQLException the SQL exception */ @SafeVarargs public static int executeUpdate(final Connection conn, final String sql, final Object... parameters) throws SQLException { N.checkArgNotNull(conn, "conn"); N.checkArgNotNull(sql, "sql"); PreparedStatement stmt = null; try { stmt = prepareStatement(conn, sql, parameters); return stmt.executeUpdate(); } finally { closeQuietly(stmt); } } /** * * @param ds * @param sql * @param listOfParameters * @return * @throws SQLException the SQL exception */ public static int executeBatchUpdate(final DataSource ds, final String sql, final List listOfParameters) throws SQLException { return executeBatchUpdate(ds, sql, listOfParameters, JdbcUtil.DEFAULT_BATCH_SIZE); } /** * * @param ds * @param sql * @param listOfParameters * @param batchSize * @return * @throws SQLException the SQL exception */ public static int executeBatchUpdate(final DataSource ds, final String sql, final List listOfParameters, final int batchSize) throws SQLException { N.checkArgNotNull(ds, "ds"); N.checkArgNotNull(sql, "sql"); N.checkArgPositive(batchSize, "batchSize"); final SQLTransaction tran = getTransaction(ds, sql, CreatedBy.JDBC_UTIL); if (tran != null) { return executeBatchUpdate(tran.connection(), sql, listOfParameters, batchSize); } else if (listOfParameters.size() <= batchSize) { final Connection conn = getConnection(ds); try { return executeBatchUpdate(conn, sql, listOfParameters, batchSize); } finally { JdbcUtil.closeQuietly(conn); } } else { final SQLTransaction tran2 = JdbcUtil.beginTransaction(ds); int ret = 0; try { ret = executeBatchUpdate(tran2.connection(), sql, listOfParameters, batchSize); tran2.commit(); } finally { tran2.rollbackIfNotCommitted(); } return ret; } } /** * Execute batch update. * * @param conn * @param sql * @param listOfParameters * @return * @throws SQLException the SQL exception */ public static int executeBatchUpdate(final Connection conn, final String sql, final List listOfParameters) throws SQLException { return executeBatchUpdate(conn, sql, listOfParameters, JdbcUtil.DEFAULT_BATCH_SIZE); } /** * Execute batch update. * * @param conn * @param sql * @param listOfParameters * @param batchSize * @return * @throws SQLException the SQL exception */ public static int executeBatchUpdate(final Connection conn, final String sql, final List listOfParameters, final int batchSize) throws SQLException { N.checkArgNotNull(conn); N.checkArgNotNull(sql); N.checkArgPositive(batchSize, "batchSize"); if (N.isNullOrEmpty(listOfParameters)) { return 0; } final NamedSQL namedSQL = NamedSQL.parse(sql); final boolean originalAutoCommit = conn.getAutoCommit(); PreparedStatement stmt = null; boolean noException = false; try { if (originalAutoCommit && listOfParameters.size() > batchSize) { conn.setAutoCommit(false); } stmt = conn.prepareStatement(namedSQL.getParameterizedSQL()); int res = 0; int idx = 0; for (Object parameters : listOfParameters) { StatementSetter.DEFAULT.setParameters(namedSQL, stmt, parameters); stmt.addBatch(); if (++idx % batchSize == 0) { res += N.sum(stmt.executeBatch()); stmt.clearBatch(); } } if (idx % batchSize != 0) { res += N.sum(stmt.executeBatch()); stmt.clearBatch(); } noException = true; return res; } finally { if (originalAutoCommit && listOfParameters.size() > batchSize) { try { if (noException) { conn.commit(); } else { conn.rollback(); } } finally { try { conn.setAutoCommit(true); } finally { JdbcUtil.closeQuietly(stmt); } } } else { JdbcUtil.closeQuietly(stmt); } } } /** * * @param ds * @param sql * @param parameters * @return * @throws SQLException the SQL exception */ @SafeVarargs public static boolean execute(final DataSource ds, final String sql, final Object... parameters) throws SQLException { N.checkArgNotNull(ds, "ds"); N.checkArgNotNull(sql, "sql"); final SQLTransaction tran = getTransaction(ds, sql, CreatedBy.JDBC_UTIL); if (tran != null) { return execute(tran.connection(), sql, parameters); } else { final Connection conn = getConnection(ds); try { return execute(conn, sql, parameters); } finally { JdbcUtil.closeQuietly(conn); } } } /** * * @param conn * @param sql * @param parameters * @return true, if successful * @throws SQLException the SQL exception */ @SafeVarargs public static boolean execute(final Connection conn, final String sql, final Object... parameters) throws SQLException { N.checkArgNotNull(conn, "conn"); N.checkArgNotNull(sql, "sql"); PreparedStatement stmt = null; try { stmt = prepareStatement(conn, sql, parameters); return stmt.execute(); } finally { closeQuietly(stmt); } } /** * * @param rs * @return * @throws SQLException the SQL exception */ public static DataSet extractData(final ResultSet rs) throws SQLException { return extractData(rs, false); } /** * * @param rs * @param closeResultSet * @return * @throws SQLException the SQL exception */ public static DataSet extractData(final ResultSet rs, final boolean closeResultSet) throws SQLException { return extractData(rs, 0, Integer.MAX_VALUE, closeResultSet); } /** * * @param rs * @param offset * @param count * @return * @throws SQLException the SQL exception */ public static DataSet extractData(final ResultSet rs, final int offset, final int count) throws SQLException { return extractData(rs, offset, count, false); } /** * * @param rs * @param offset * @param count * @param closeResultSet * @return * @throws SQLException the SQL exception */ public static DataSet extractData(final ResultSet rs, final int offset, final int count, final boolean closeResultSet) throws SQLException { return extractData(rs, offset, count, RowFilter.ALWAYS_TRUE, closeResultSet); } /** * * @param rs * @param offset * @param count * @param filter * @param closeResultSet * @return * @throws SQLException the SQL exception */ public static DataSet extractData(final ResultSet rs, int offset, int count, final RowFilter filter, final boolean closeResultSet) throws SQLException { N.checkArgNotNull(rs, "ResultSet"); N.checkArgNotNegative(offset, "offset"); N.checkArgNotNegative(count, "count"); N.checkArgNotNull(filter, "filter"); try { // TODO [performance improvement]. it will improve performance a lot if MetaData is cached. final ResultSetMetaData rsmd = rs.getMetaData(); final int columnCount = rsmd.getColumnCount(); final List columnNameList = new ArrayList<>(columnCount); final List> columnList = new ArrayList<>(columnCount); for (int i = 0; i < columnCount;) { columnNameList.add(JdbcUtil.getColumnLabel(rsmd, ++i)); columnList.add(new ArrayList<>()); } JdbcUtil.skip(rs, offset); while (count > 0 && rs.next()) { if (filter == null || filter.test(rs)) { for (int i = 0; i < columnCount;) { columnList.get(i).add(JdbcUtil.getColumnValue(rs, ++i)); } count--; } } // return new RowDataSet(null, entityClass, columnNameList, columnList); return new RowDataSet(columnNameList, columnList); } finally { if (closeResultSet) { closeQuietly(rs); } } } /** * Does table exist. * * @param conn * @param tableName * @return true, if successful */ public static boolean doesTableExist(final Connection conn, final String tableName) { try { executeQuery(conn, "SELECT 1 FROM " + tableName + " WHERE 1 > 2"); return true; } catch (SQLException e) { if (isTableNotExistsException(e)) { return false; } throw new UncheckedSQLException(e); } } /** * Returns {@code true} if succeed to create table, otherwise {@code false} is returned. * * @param conn * @param tableName * @param schema * @return true, if successful */ public static boolean createTableIfNotExists(final Connection conn, final String tableName, final String schema) { if (doesTableExist(conn, tableName)) { return false; } try { execute(conn, schema); return true; } catch (SQLException e) { return false; } } /** * Returns {@code true} if succeed to drop table, otherwise {@code false} is returned. * * @param conn * @param tableName * @return true, if successful */ public static boolean dropTableIfExists(final Connection conn, final String tableName) { try { if (doesTableExist(conn, tableName)) { execute(conn, "DROP TABLE " + tableName); return true; } } catch (SQLException e) { // ignore. } return false; } /** * Gets the named parameters. * * @param sql * @return */ public static List getNamedParameters(String sql) { return NamedSQL.parse(sql).getNamedParameters(); } /** * Imports the data from DataSet to database. * * @param dataset * @param conn * @param insertSQL the column order in the sql must be consistent with the column order in the DataSet. Here is sample about how to create the sql: *

     *         List columnNameList = new ArrayList<>(dataset.columnNameList());
     *         columnNameList.retainAll(yourSelectColumnNames);
     *         String sql = RE.insert(columnNameList).into(tableName).sql();
     * 
* @return * @throws UncheckedSQLException the unchecked SQL exception */ public static int importData(final DataSet dataset, final Connection conn, final String insertSQL) throws UncheckedSQLException { return importData(dataset, dataset.columnNameList(), conn, insertSQL); } /** * Imports the data from DataSet to database. * * @param dataset * @param selectColumnNames * @param conn * @param insertSQL the column order in the sql must be consistent with the column order in the DataSet. Here is sample about how to create the sql: *

     *         List columnNameList = new ArrayList<>(dataset.columnNameList());
     *         columnNameList.retainAll(yourSelectColumnNames);
     *         String sql = RE.insert(columnNameList).into(tableName).sql();
     * 
* @return * @throws UncheckedSQLException the unchecked SQL exception */ public static int importData(final DataSet dataset, final Collection selectColumnNames, final Connection conn, final String insertSQL) throws UncheckedSQLException { return importData(dataset, selectColumnNames, 0, dataset.size(), conn, insertSQL); } /** * Imports the data from DataSet to database. * * @param dataset * @param selectColumnNames * @param offset * @param count * @param conn * @param insertSQL the column order in the sql must be consistent with the column order in the DataSet. Here is sample about how to create the sql: *

     *         List columnNameList = new ArrayList<>(dataset.columnNameList());
     *         columnNameList.retainAll(yourSelectColumnNames);
     *         String sql = RE.insert(columnNameList).into(tableName).sql();
     * 
* @return * @throws UncheckedSQLException the unchecked SQL exception */ public static int importData(final DataSet dataset, final Collection selectColumnNames, final int offset, final int count, final Connection conn, final String insertSQL) throws UncheckedSQLException { return importData(dataset, selectColumnNames, offset, count, conn, insertSQL, 200, 0); } /** * Imports the data from DataSet to database. * * @param dataset * @param selectColumnNames * @param offset * @param count * @param conn * @param insertSQL the column order in the sql must be consistent with the column order in the DataSet. Here is sample about how to create the sql: *

     *         List columnNameList = new ArrayList<>(dataset.columnNameList());
     *         columnNameList.retainAll(yourSelectColumnNames);
     *         String sql = RE.insert(columnNameList).into(tableName).sql();
     * 
* @param batchSize * @param batchInterval * @return * @throws UncheckedSQLException the unchecked SQL exception */ public static int importData(final DataSet dataset, final Collection selectColumnNames, final int offset, final int count, final Connection conn, final String insertSQL, final int batchSize, final int batchInterval) throws UncheckedSQLException { return importData(dataset, selectColumnNames, offset, count, Fn.alwaysTrue(), conn, insertSQL, batchSize, batchInterval); } /** * Imports the data from DataSet to database. * * @param * @param dataset * @param selectColumnNames * @param offset * @param count * @param filter * @param conn * @param insertSQL the column order in the sql must be consistent with the column order in the DataSet. Here is sample about how to create the sql: *

     *         List columnNameList = new ArrayList<>(dataset.columnNameList());
     *         columnNameList.retainAll(yourSelectColumnNames);
     *         String sql = RE.insert(columnNameList).into(tableName).sql();
     * 
* @param batchSize * @param batchInterval * @return * @throws UncheckedSQLException the unchecked SQL exception * @throws E the e */ public static int importData(final DataSet dataset, final Collection selectColumnNames, final int offset, final int count, final Try.Predicate filter, final Connection conn, final String insertSQL, final int batchSize, final int batchInterval) throws UncheckedSQLException, E { PreparedStatement stmt = null; try { stmt = prepareStatement(conn, insertSQL); return importData(dataset, selectColumnNames, offset, count, filter, stmt, batchSize, batchInterval); } catch (SQLException e) { throw new UncheckedSQLException(e); } finally { JdbcUtil.closeQuietly(stmt); } } /** * Imports the data from DataSet to database. * * @param dataset * @param conn * @param insertSQL the column order in the sql must be consistent with the column order in the DataSet. Here is sample about how to create the sql: *

     *         List columnNameList = new ArrayList<>(dataset.columnNameList());
     *         columnNameList.retainAll(yourSelectColumnNames);
     *         String sql = RE.insert(columnNameList).into(tableName).sql();
     * 
* @param columnTypeMap * @return * @throws UncheckedSQLException the unchecked SQL exception */ @SuppressWarnings("rawtypes") public static int importData(final DataSet dataset, final Connection conn, final String insertSQL, final Map columnTypeMap) throws UncheckedSQLException { return importData(dataset, 0, dataset.size(), conn, insertSQL, columnTypeMap); } /** * Imports the data from DataSet to database. * * @param dataset * @param offset * @param count * @param conn * @param insertSQL the column order in the sql must be consistent with the column order in the DataSet. Here is sample about how to create the sql: *

     *         List columnNameList = new ArrayList<>(dataset.columnNameList());
     *         columnNameList.retainAll(yourSelectColumnNames);
     *         String sql = RE.insert(columnNameList).into(tableName).sql();
     * 
* @param columnTypeMap * @return * @throws UncheckedSQLException the unchecked SQL exception */ @SuppressWarnings("rawtypes") public static int importData(final DataSet dataset, final int offset, final int count, final Connection conn, final String insertSQL, final Map columnTypeMap) throws UncheckedSQLException { return importData(dataset, offset, count, conn, insertSQL, 200, 0, columnTypeMap); } /** * Imports the data from DataSet to database. * * @param dataset * @param offset * @param count * @param conn * @param insertSQL the column order in the sql must be consistent with the column order in the DataSet. Here is sample about how to create the sql: *

     *         List columnNameList = new ArrayList<>(dataset.columnNameList());
     *         columnNameList.retainAll(yourSelectColumnNames);
     *         String sql = RE.insert(columnNameList).into(tableName).sql();
     * 
* @param batchSize * @param batchInterval * @param columnTypeMap * @return * @throws UncheckedSQLException the unchecked SQL exception */ @SuppressWarnings("rawtypes") public static int importData(final DataSet dataset, final int offset, final int count, final Connection conn, final String insertSQL, final int batchSize, final int batchInterval, final Map columnTypeMap) throws UncheckedSQLException { return importData(dataset, offset, count, Fn.alwaysTrue(), conn, insertSQL, batchSize, batchInterval, columnTypeMap); } /** * Imports the data from DataSet to database. * * @param * @param dataset * @param offset * @param count * @param filter * @param conn * @param insertSQL the column order in the sql must be consistent with the column order in the DataSet. Here is sample about how to create the sql: *

     *         List columnNameList = new ArrayList<>(dataset.columnNameList());
     *         columnNameList.retainAll(yourSelectColumnNames);
     *         String sql = RE.insert(columnNameList).into(tableName).sql();
     * 
* @param batchSize * @param batchInterval * @param columnTypeMap * @return * @throws UncheckedSQLException the unchecked SQL exception * @throws E the e */ @SuppressWarnings("rawtypes") public static int importData(final DataSet dataset, final int offset, final int count, final Try.Predicate filter, final Connection conn, final String insertSQL, final int batchSize, final int batchInterval, final Map columnTypeMap) throws UncheckedSQLException, E { PreparedStatement stmt = null; try { stmt = prepareStatement(conn, insertSQL); return importData(dataset, offset, count, filter, stmt, batchSize, batchInterval, columnTypeMap); } catch (SQLException e) { throw new UncheckedSQLException(e); } finally { JdbcUtil.closeQuietly(stmt); } } /** * Imports the data from DataSet to database. * * @param dataset * @param conn * @param insertSQL the column order in the sql must be consistent with the column order in the DataSet. Here is sample about how to create the sql: *

     *         List columnNameList = new ArrayList<>(dataset.columnNameList());
     *         columnNameList.retainAll(yourSelectColumnNames);
     *         String sql = RE.insert(columnNameList).into(tableName).sql();
     * 
* @param stmtSetter * @return * @throws UncheckedSQLException the unchecked SQL exception */ public static int importData(final DataSet dataset, final Connection conn, final String insertSQL, final JdbcUtil.BiParametersSetter stmtSetter) throws UncheckedSQLException { return importData(dataset, 0, dataset.size(), conn, insertSQL, stmtSetter); } /** * Imports the data from DataSet to database. * * @param dataset * @param offset * @param count * @param conn * @param insertSQL the column order in the sql must be consistent with the column order in the DataSet. Here is sample about how to create the sql: *

     *         List columnNameList = new ArrayList<>(dataset.columnNameList());
     *         columnNameList.retainAll(yourSelectColumnNames);
     *         String sql = RE.insert(columnNameList).into(tableName).sql();
     * 
* @param stmtSetter * @return * @throws UncheckedSQLException the unchecked SQL exception */ public static int importData(final DataSet dataset, final int offset, final int count, final Connection conn, final String insertSQL, final JdbcUtil.BiParametersSetter stmtSetter) throws UncheckedSQLException { return importData(dataset, offset, count, conn, insertSQL, 200, 0, stmtSetter); } /** * Imports the data from DataSet to database. * * @param dataset * @param offset * @param count * @param conn * @param insertSQL the column order in the sql must be consistent with the column order in the DataSet. Here is sample about how to create the sql: *

     *         List columnNameList = new ArrayList<>(dataset.columnNameList());
     *         columnNameList.retainAll(yourSelectColumnNames);
     *         String sql = RE.insert(columnNameList).into(tableName).sql();
     * 
* @param batchSize * @param batchInterval * @param stmtSetter * @return * @throws UncheckedSQLException the unchecked SQL exception */ public static int importData(final DataSet dataset, final int offset, final int count, final Connection conn, final String insertSQL, final int batchSize, final int batchInterval, final JdbcUtil.BiParametersSetter stmtSetter) throws UncheckedSQLException { return importData(dataset, offset, count, Fn.alwaysTrue(), conn, insertSQL, batchSize, batchInterval, stmtSetter); } /** * Imports the data from DataSet to database. * * @param * @param dataset * @param offset * @param count * @param filter * @param conn * @param insertSQL the column order in the sql must be consistent with the column order in the DataSet. Here is sample about how to create the sql: *

     *         List columnNameList = new ArrayList<>(dataset.columnNameList());
     *         columnNameList.retainAll(yourSelectColumnNames);
     *         String sql = RE.insert(columnNameList).into(tableName).sql();
     * 
* @param batchSize * @param batchInterval * @param stmtSetter * @return * @throws UncheckedSQLException the unchecked SQL exception * @throws E the e */ public static int importData(final DataSet dataset, final int offset, final int count, final Try.Predicate filter, final Connection conn, final String insertSQL, final int batchSize, final int batchInterval, final JdbcUtil.BiParametersSetter stmtSetter) throws UncheckedSQLException, E { PreparedStatement stmt = null; try { stmt = prepareStatement(conn, insertSQL); return importData(dataset, offset, count, filter, stmt, batchSize, batchInterval, stmtSetter); } catch (SQLException e) { throw new UncheckedSQLException(e); } finally { JdbcUtil.closeQuietly(stmt); } } /** * Imports the data from DataSet to database. * * @param dataset * @param stmt the column order in the sql must be consistent with the column order in the DataSet. * @return * @throws UncheckedSQLException the unchecked SQL exception */ public static int importData(final DataSet dataset, final PreparedStatement stmt) throws UncheckedSQLException { return importData(dataset, dataset.columnNameList(), stmt); } /** * Imports the data from DataSet to database. * * @param dataset * @param selectColumnNames * @param stmt the column order in the sql must be consistent with the column order in the DataSet. * @return * @throws UncheckedSQLException the unchecked SQL exception */ public static int importData(final DataSet dataset, final Collection selectColumnNames, final PreparedStatement stmt) throws UncheckedSQLException { return importData(dataset, selectColumnNames, 0, dataset.size(), stmt); } /** * Imports the data from DataSet to database. * * @param dataset * @param selectColumnNames * @param offset * @param count * @param stmt the column order in the sql must be consistent with the column order in the DataSet. * @return * @throws UncheckedSQLException the unchecked SQL exception */ public static int importData(final DataSet dataset, final Collection selectColumnNames, final int offset, final int count, final PreparedStatement stmt) throws UncheckedSQLException { return importData(dataset, selectColumnNames, offset, count, stmt, 200, 0); } /** * Imports the data from DataSet to database. * * @param dataset * @param selectColumnNames * @param offset * @param count * @param stmt the column order in the sql must be consistent with the column order in the DataSet. * @param batchSize * @param batchInterval * @return * @throws UncheckedSQLException the unchecked SQL exception */ public static int importData(final DataSet dataset, final Collection selectColumnNames, final int offset, final int count, final PreparedStatement stmt, final int batchSize, final int batchInterval) throws UncheckedSQLException { return importData(dataset, selectColumnNames, offset, count, Fn.alwaysTrue(), stmt, batchSize, batchInterval); } /** * Imports the data from DataSet to database. * * @param * @param dataset * @param selectColumnNames * @param offset * @param count * @param filter * @param stmt the column order in the sql must be consistent with the column order in the DataSet. * @param batchSize * @param batchInterval * @return * @throws UncheckedSQLException the unchecked SQL exception * @throws E the e */ public static int importData(final DataSet dataset, final Collection selectColumnNames, final int offset, final int count, final Try.Predicate filter, final PreparedStatement stmt, final int batchSize, final int batchInterval) throws UncheckedSQLException, E { final Type objType = N.typeOf(Object.class); final Map> columnTypeMap = new HashMap<>(); for (String propName : selectColumnNames) { columnTypeMap.put(propName, objType); } return importData(dataset, offset, count, filter, stmt, batchSize, batchInterval, columnTypeMap); } /** * Imports the data from DataSet to database. * * @param dataset * @param stmt the column order in the sql must be consistent with the column order in the DataSet. * @param columnTypeMap * @return * @throws UncheckedSQLException the unchecked SQL exception */ @SuppressWarnings("rawtypes") public static int importData(final DataSet dataset, final PreparedStatement stmt, final Map columnTypeMap) throws UncheckedSQLException { return importData(dataset, 0, dataset.size(), stmt, columnTypeMap); } /** * Imports the data from DataSet to database. * * @param dataset * @param offset * @param count * @param stmt the column order in the sql must be consistent with the column order in the DataSet. * @param columnTypeMap * @return * @throws UncheckedSQLException the unchecked SQL exception */ @SuppressWarnings("rawtypes") public static int importData(final DataSet dataset, final int offset, final int count, final PreparedStatement stmt, final Map columnTypeMap) throws UncheckedSQLException { return importData(dataset, offset, count, stmt, 200, 0, columnTypeMap); } /** * Imports the data from DataSet to database. * * @param dataset * @param offset * @param count * @param stmt the column order in the sql must be consistent with the column order in the DataSet. * @param batchSize * @param batchInterval * @param columnTypeMap * @return * @throws UncheckedSQLException the unchecked SQL exception */ @SuppressWarnings("rawtypes") public static int importData(final DataSet dataset, final int offset, final int count, final PreparedStatement stmt, final int batchSize, final int batchInterval, final Map columnTypeMap) throws UncheckedSQLException { return importData(dataset, offset, count, Fn.alwaysTrue(), stmt, batchSize, batchInterval, columnTypeMap); } /** * Imports the data from DataSet to database. * * @param * @param dataset * @param offset * @param count * @param filter * @param stmt the column order in the sql must be consistent with the column order in the DataSet. * @param batchSize * @param batchInterval * @param columnTypeMap * @return * @throws UncheckedSQLException the unchecked SQL exception * @throws E the e */ @SuppressWarnings("rawtypes") public static int importData(final DataSet dataset, final int offset, final int count, final Try.Predicate filter, final PreparedStatement stmt, final int batchSize, final int batchInterval, final Map columnTypeMap) throws UncheckedSQLException, E { N.checkArgument(offset >= 0 && count >= 0, "'offset'=%s and 'count'=%s can't be negative", offset, count); N.checkArgument(batchSize > 0 && batchInterval >= 0, "'batchSize'=%s must be greater than 0 and 'batchInterval'=%s can't be negative", batchSize, batchInterval); int result = 0; try { final int columnCount = columnTypeMap.size(); final List columnNameList = dataset.columnNameList(); final int[] columnIndexes = new int[columnCount]; final Type[] columnTypes = new Type[columnCount]; final Set columnNameSet = N.newHashSet(columnCount); int idx = 0; for (String columnName : columnNameList) { if (columnTypeMap.containsKey(columnName)) { columnIndexes[idx] = dataset.getColumnIndex(columnName); columnTypes[idx] = columnTypeMap.get(columnName); columnNameSet.add(columnName); idx++; } } if (columnNameSet.size() != columnTypeMap.size()) { final List keys = new ArrayList<>(columnTypeMap.keySet()); keys.removeAll(columnNameSet); throw new AbacusException(keys + " are not included in titles: " + N.toString(columnNameList)); } final Object[] row = filter == null ? null : new Object[columnCount]; for (int i = offset, size = dataset.size(); result < count && i < size; i++) { dataset.absolute(i); if (filter == null) { for (int j = 0; j < columnCount; j++) { columnTypes[j].set(stmt, j + 1, dataset.get(columnIndexes[j])); } } else { for (int j = 0; j < columnCount; j++) { row[j] = dataset.get(columnIndexes[j]); } if (filter.test(row) == false) { continue; } for (int j = 0; j < columnCount; j++) { columnTypes[j].set(stmt, j + 1, row[j]); } } stmt.addBatch(); if ((++result % batchSize) == 0) { stmt.executeBatch(); stmt.clearBatch(); if (batchInterval > 0) { N.sleep(batchInterval); } } } if ((result % batchSize) > 0) { stmt.executeBatch(); stmt.clearBatch(); } } catch (SQLException e) { throw new UncheckedSQLException(e); } return result; } /** * * @param dataset * @param stmt * @param stmtSetter * @return * @throws UncheckedSQLException the unchecked SQL exception */ public static int importData(final DataSet dataset, final PreparedStatement stmt, final JdbcUtil.BiParametersSetter stmtSetter) throws UncheckedSQLException { return importData(dataset, 0, dataset.size(), stmt, stmtSetter); } /** * Imports the data from DataSet to database. * * @param dataset * @param offset * @param count * @param stmt the column order in the sql must be consistent with the column order in the DataSet. * @param stmtSetter * @return * @throws UncheckedSQLException the unchecked SQL exception */ public static int importData(final DataSet dataset, final int offset, final int count, final PreparedStatement stmt, final JdbcUtil.BiParametersSetter stmtSetter) throws UncheckedSQLException { return importData(dataset, offset, count, stmt, 200, 0, stmtSetter); } /** * Imports the data from DataSet to database. * * @param dataset * @param offset * @param count * @param stmt the column order in the sql must be consistent with the column order in the DataSet. * @param batchSize * @param batchInterval * @param stmtSetter * @return * @throws UncheckedSQLException the unchecked SQL exception */ public static int importData(final DataSet dataset, final int offset, final int count, final PreparedStatement stmt, final int batchSize, final int batchInterval, final JdbcUtil.BiParametersSetter stmtSetter) throws UncheckedSQLException { return importData(dataset, offset, count, Fn.alwaysTrue(), stmt, batchSize, batchInterval, stmtSetter); } /** * Imports the data from DataSet to database. * * @param * @param dataset * @param offset * @param count * @param filter * @param stmt the column order in the sql must be consistent with the column order in the DataSet. * @param batchSize * @param batchInterval * @param stmtSetter * @return * @throws UncheckedSQLException the unchecked SQL exception * @throws E the e */ public static int importData(final DataSet dataset, final int offset, final int count, final Try.Predicate filter, final PreparedStatement stmt, final int batchSize, final int batchInterval, final JdbcUtil.BiParametersSetter stmtSetter) throws UncheckedSQLException, E { N.checkArgument(offset >= 0 && count >= 0, "'offset'=%s and 'count'=%s can't be negative", offset, count); N.checkArgument(batchSize > 0 && batchInterval >= 0, "'batchSize'=%s must be greater than 0 and 'batchInterval'=%s can't be negative", batchSize, batchInterval); final int columnCount = dataset.columnNameList().size(); final Object[] row = new Object[columnCount]; int result = 0; try { for (int i = offset, size = dataset.size(); result < count && i < size; i++) { dataset.absolute(i); for (int j = 0; j < columnCount; j++) { row[j] = dataset.get(j); } if (filter != null && filter.test(row) == false) { continue; } stmtSetter.accept(stmt, row); stmt.addBatch(); if ((++result % batchSize) == 0) { stmt.executeBatch(); stmt.clearBatch(); if (batchInterval > 0) { N.sleep(batchInterval); } } } if ((result % batchSize) > 0) { stmt.executeBatch(); stmt.clearBatch(); } } catch (SQLException e) { throw new UncheckedSQLException(e); } return result; } /** * * @param * @param file * @param conn * @param insertSQL * @param func * @return * @throws UncheckedSQLException the unchecked SQL exception * @throws E the e */ public static long importData(final File file, final Connection conn, final String insertSQL, final Try.Function func) throws UncheckedSQLException, E { return importData(file, 0, Long.MAX_VALUE, conn, insertSQL, 200, 0, func); } /** * * @param * @param file * @param offset * @param count * @param conn * @param insertSQL * @param batchSize * @param batchInterval * @param func * @return * @throws UncheckedSQLException the unchecked SQL exception * @throws E the e */ public static long importData(final File file, final long offset, final long count, final Connection conn, final String insertSQL, final int batchSize, final int batchInterval, final Try.Function func) throws UncheckedSQLException, E { PreparedStatement stmt = null; try { stmt = prepareStatement(conn, insertSQL); return importData(file, offset, count, stmt, batchSize, batchInterval, func); } catch (SQLException e) { throw new UncheckedSQLException(e); } finally { JdbcUtil.closeQuietly(stmt); } } /** * * @param * @param file * @param stmt * @param func * @return * @throws UncheckedSQLException the unchecked SQL exception * @throws E the e */ public static long importData(final File file, final PreparedStatement stmt, final Try.Function func) throws UncheckedSQLException, E { return importData(file, 0, Long.MAX_VALUE, stmt, 200, 0, func); } /** * Imports the data from file to database. * * @param * @param file * @param offset * @param count * @param stmt * @param batchSize * @param batchInterval * @param func convert line to the parameters for record insert. Returns a null array to skip the line. * @return * @throws UncheckedSQLException the unchecked SQL exception * @throws E the e */ public static long importData(final File file, final long offset, final long count, final PreparedStatement stmt, final int batchSize, final int batchInterval, final Try.Function func) throws UncheckedSQLException, E { Reader reader = null; try { reader = new FileReader(file); return importData(reader, offset, count, stmt, batchSize, batchInterval, func); } catch (IOException e) { throw new UncheckedIOException(e); } finally { IOUtil.close(reader); } } /** * * @param * @param is * @param conn * @param insertSQL * @param func * @return * @throws UncheckedSQLException the unchecked SQL exception * @throws E the e */ public static long importData(final InputStream is, final Connection conn, final String insertSQL, final Try.Function func) throws UncheckedSQLException, E { return importData(is, 0, Long.MAX_VALUE, conn, insertSQL, 200, 0, func); } /** * * @param * @param is * @param offset * @param count * @param conn * @param insertSQL * @param batchSize * @param batchInterval * @param func * @return * @throws UncheckedSQLException the unchecked SQL exception * @throws E the e */ public static long importData(final InputStream is, final long offset, final long count, final Connection conn, final String insertSQL, final int batchSize, final int batchInterval, final Try.Function func) throws UncheckedSQLException, E { PreparedStatement stmt = null; try { stmt = prepareStatement(conn, insertSQL); return importData(is, offset, count, stmt, batchSize, batchInterval, func); } catch (SQLException e) { throw new UncheckedSQLException(e); } finally { JdbcUtil.closeQuietly(stmt); } } /** * * @param * @param is * @param stmt * @param func * @return * @throws E the e */ public static long importData(final InputStream is, final PreparedStatement stmt, final Try.Function func) throws E { return importData(is, 0, Long.MAX_VALUE, stmt, 200, 0, func); } /** * Imports the data from file to database. * * @param * @param is * @param offset * @param count * @param stmt * @param batchSize * @param batchInterval * @param func convert line to the parameters for record insert. Returns a null array to skip the line. * @return * @throws UncheckedSQLException the unchecked SQL exception * @throws E the e */ public static long importData(final InputStream is, final long offset, final long count, final PreparedStatement stmt, final int batchSize, final int batchInterval, final Try.Function func) throws UncheckedSQLException, E { final Reader reader = new InputStreamReader(is); return importData(reader, offset, count, stmt, batchSize, batchInterval, func); } /** * * @param * @param reader * @param conn * @param insertSQL * @param func * @return * @throws UncheckedSQLException the unchecked SQL exception * @throws E the e */ public static long importData(final Reader reader, final Connection conn, final String insertSQL, final Try.Function func) throws UncheckedSQLException, E { return importData(reader, 0, Long.MAX_VALUE, conn, insertSQL, 200, 0, func); } /** * * @param * @param reader * @param offset * @param count * @param conn * @param insertSQL * @param batchSize * @param batchInterval * @param func * @return * @throws UncheckedSQLException the unchecked SQL exception * @throws E the e */ public static long importData(final Reader reader, final long offset, final long count, final Connection conn, final String insertSQL, final int batchSize, final int batchInterval, final Try.Function func) throws UncheckedSQLException, E { PreparedStatement stmt = null; try { stmt = prepareStatement(conn, insertSQL); return importData(reader, offset, count, stmt, batchSize, batchInterval, func); } catch (SQLException e) { throw new UncheckedSQLException(e); } finally { JdbcUtil.closeQuietly(stmt); } } /** * * @param * @param reader * @param stmt * @param func * @return * @throws E the e */ public static long importData(final Reader reader, final PreparedStatement stmt, final Try.Function func) throws E { return importData(reader, 0, Long.MAX_VALUE, stmt, 200, 0, func); } /** * Imports the data from file to database. * * @param * @param reader * @param offset * @param count * @param stmt * @param batchSize * @param batchInterval * @param func convert line to the parameters for record insert. Returns a null array to skip the line. * @return * @throws UncheckedSQLException the unchecked SQL exception * @throws E the e */ public static long importData(final Reader reader, long offset, final long count, final PreparedStatement stmt, final int batchSize, final int batchInterval, final Try.Function func) throws UncheckedSQLException, E { N.checkArgument(offset >= 0 && count >= 0, "'offset'=%s and 'count'=%s can't be negative", offset, count); N.checkArgument(batchSize > 0 && batchInterval >= 0, "'batchSize'=%s must be greater than 0 and 'batchInterval'=%s can't be negative", batchSize, batchInterval); long result = 0; final BufferedReader br = Objectory.createBufferedReader(reader); try { while (offset-- > 0 && br.readLine() != null) { } String line = null; Object[] row = null; while (result < count && (line = br.readLine()) != null) { row = func.apply(line); if (row == null) { continue; } for (int i = 0, len = row.length; i < len; i++) { stmt.setObject(i + 1, row[i]); } stmt.addBatch(); if ((++result % batchSize) == 0) { stmt.executeBatch(); stmt.clearBatch(); if (batchInterval > 0) { N.sleep(batchInterval); } } } if ((result % batchSize) > 0) { stmt.executeBatch(); stmt.clearBatch(); } } catch (SQLException e) { throw new UncheckedSQLException(e); } catch (IOException e) { throw new UncheckedIOException(e); } finally { Objectory.recycle(br); } return result; } /** * * @param * @param * @param iter * @param conn * @param insertSQL * @param func * @return * @throws UncheckedSQLException the unchecked SQL exception * @throws E the e */ public static long importData(final Iterator iter, final Connection conn, final String insertSQL, final Try.Function func) throws UncheckedSQLException, E { return importData(iter, 0, Long.MAX_VALUE, conn, insertSQL, 200, 0, func); } /** * * @param * @param * @param iter * @param offset * @param count * @param conn * @param insertSQL * @param batchSize * @param batchInterval * @param func * @return * @throws UncheckedSQLException the unchecked SQL exception * @throws E the e */ public static long importData(final Iterator iter, final long offset, final long count, final Connection conn, final String insertSQL, final int batchSize, final int batchInterval, final Try.Function func) throws UncheckedSQLException, E { PreparedStatement stmt = null; try { stmt = prepareStatement(conn, insertSQL); return importData(iter, offset, count, stmt, batchSize, batchInterval, func); } catch (SQLException e) { throw new UncheckedSQLException(e); } finally { JdbcUtil.closeQuietly(stmt); } } /** * * @param * @param * @param iter * @param stmt * @param func * @return * @throws E the e */ public static long importData(final Iterator iter, final PreparedStatement stmt, final Try.Function func) throws E { return importData(iter, 0, Long.MAX_VALUE, stmt, 200, 0, func); } /** * Imports the data from Iterator to database. * * @param * @param * @param iter * @param offset * @param count * @param stmt * @param batchSize * @param batchInterval * @param func convert element to the parameters for record insert. Returns a null array to skip the line. * @return * @throws UncheckedSQLException the unchecked SQL exception * @throws E the e */ public static long importData(final Iterator iter, long offset, final long count, final PreparedStatement stmt, final int batchSize, final int batchInterval, final Try.Function func) throws UncheckedSQLException, E { N.checkArgument(offset >= 0 && count >= 0, "'offset'=%s and 'count'=%s can't be negative", offset, count); N.checkArgument(batchSize > 0 && batchInterval >= 0, "'batchSize'=%s must be greater than 0 and 'batchInterval'=%s can't be negative", batchSize, batchInterval); long result = 0; try { while (offset-- > 0 && iter.hasNext()) { iter.next(); } Object[] row = null; while (result < count && iter.hasNext()) { row = func.apply(iter.next()); if (row == null) { continue; } for (int i = 0, len = row.length; i < len; i++) { stmt.setObject(i + 1, row[i]); } stmt.addBatch(); if ((++result % batchSize) == 0) { stmt.executeBatch(); stmt.clearBatch(); if (batchInterval > 0) { N.sleep(batchInterval); } } } if ((result % batchSize) > 0) { stmt.executeBatch(); stmt.clearBatch(); } } catch (SQLException e) { throw new UncheckedSQLException(e); } return result; } /** * * @param * @param iter * @param conn * @param insertSQL * @param stmtSetter * @return */ public static long importData(final Iterator iter, final Connection conn, final String insertSQL, final JdbcUtil.BiParametersSetter stmtSetter) { return importData(iter, 0, Long.MAX_VALUE, conn, insertSQL, 200, 0, stmtSetter); } /** * * @param * @param iter * @param offset * @param count * @param conn * @param insertSQL * @param batchSize * @param batchInterval * @param stmtSetter * @return */ public static long importData(final Iterator iter, final long offset, final long count, final Connection conn, final String insertSQL, final int batchSize, final int batchInterval, final JdbcUtil.BiParametersSetter stmtSetter) { return importData(iter, offset, count, Fn.alwaysTrue(), conn, insertSQL, batchSize, batchInterval, stmtSetter); } /** * * @param * @param * @param iter * @param offset * @param count * @param filter * @param conn * @param insertSQL * @param batchSize * @param batchInterval * @param stmtSetter * @return * @throws UncheckedSQLException the unchecked SQL exception * @throws E the e */ public static long importData(final Iterator iter, final long offset, final long count, final Try.Predicate filter, final Connection conn, final String insertSQL, final int batchSize, final int batchInterval, final JdbcUtil.BiParametersSetter stmtSetter) throws UncheckedSQLException, E { PreparedStatement stmt = null; try { stmt = prepareStatement(conn, insertSQL); return importData(iter, offset, count, filter, stmt, batchSize, batchInterval, stmtSetter); } catch (SQLException e) { throw new UncheckedSQLException(e); } finally { JdbcUtil.closeQuietly(stmt); } } /** * * @param * @param iter * @param stmt * @param stmtSetter * @return */ public static long importData(final Iterator iter, final PreparedStatement stmt, final JdbcUtil.BiParametersSetter stmtSetter) { return importData(iter, 0, Long.MAX_VALUE, stmt, 200, 0, stmtSetter); } /** * * @param * @param iter * @param offset * @param count * @param stmt * @param batchSize * @param batchInterval * @param stmtSetter * @return */ public static long importData(final Iterator iter, long offset, final long count, final PreparedStatement stmt, final int batchSize, final int batchInterval, final JdbcUtil.BiParametersSetter stmtSetter) { return importData(iter, offset, count, Fn.alwaysTrue(), stmt, batchSize, batchInterval, stmtSetter); } /** * Imports the data from Iterator to database. * * @param * @param * @param iter * @param offset * @param count * @param filter * @param stmt * @param batchSize * @param batchInterval * @param stmtSetter * @return * @throws UncheckedSQLException the unchecked SQL exception * @throws E the e */ public static long importData(final Iterator iter, long offset, final long count, final Try.Predicate filter, final PreparedStatement stmt, final int batchSize, final int batchInterval, final JdbcUtil.BiParametersSetter stmtSetter) throws UncheckedSQLException, E { N.checkArgument(offset >= 0 && count >= 0, "'offset'=%s and 'count'=%s can't be negative", offset, count); N.checkArgument(batchSize > 0 && batchInterval >= 0, "'batchSize'=%s must be greater than 0 and 'batchInterval'=%s can't be negative", batchSize, batchInterval); long result = 0; try { while (offset-- > 0 && iter.hasNext()) { iter.next(); } T next = null; while (result < count && iter.hasNext()) { next = iter.next(); if (filter != null && filter.test(next) == false) { continue; } stmtSetter.accept(stmt, next); stmt.addBatch(); if ((++result % batchSize) == 0) { stmt.executeBatch(); stmt.clearBatch(); if (batchInterval > 0) { N.sleep(batchInterval); } } } if ((result % batchSize) > 0) { stmt.executeBatch(); stmt.clearBatch(); } } catch (SQLException e) { throw new UncheckedSQLException(e); } return result; } /** * * @param * @param conn * @param sql * @param rowParser * @throws UncheckedSQLException the unchecked SQL exception * @throws E the e */ public static void parse(final Connection conn, final String sql, final Try.Consumer rowParser) throws UncheckedSQLException, E { parse(conn, sql, rowParser, Fn.emptyAction()); } /** * * @param * @param * @param conn * @param sql * @param rowParser * @param onComplete * @throws UncheckedSQLException the unchecked SQL exception * @throws E the e * @throws E2 the e2 */ public static void parse(final Connection conn, final String sql, final Try.Consumer rowParser, final Try.Runnable onComplete) throws UncheckedSQLException, E, E2 { parse(conn, sql, 0, Long.MAX_VALUE, rowParser, onComplete); } /** * * @param * @param conn * @param sql * @param offset * @param count * @param rowParser * @throws UncheckedSQLException the unchecked SQL exception * @throws E the e */ public static void parse(final Connection conn, final String sql, final long offset, final long count, final Try.Consumer rowParser) throws UncheckedSQLException, E { parse(conn, sql, offset, count, rowParser, Fn.emptyAction()); } /** * * @param * @param * @param conn * @param sql * @param offset * @param count * @param rowParser * @param onComplete * @throws UncheckedSQLException the unchecked SQL exception * @throws E the e * @throws E2 the e2 */ public static void parse(final Connection conn, final String sql, final long offset, final long count, final Try.Consumer rowParser, final Try.Runnable onComplete) throws UncheckedSQLException, E, E2 { parse(conn, sql, offset, count, 0, 0, rowParser, onComplete); } /** * * @param * @param conn * @param sql * @param offset * @param count * @param processThreadNum * @param queueSize * @param rowParser * @throws UncheckedSQLException the unchecked SQL exception * @throws E the e */ public static void parse(final Connection conn, final String sql, final long offset, final long count, final int processThreadNum, final int queueSize, final Try.Consumer rowParser) throws UncheckedSQLException, E { parse(conn, sql, offset, count, processThreadNum, queueSize, rowParser, Fn.emptyAction()); } /** * Parse the ResultSet obtained by executing query with the specified Connection and sql. * * @param * @param * @param conn * @param sql * @param offset * @param count * @param processThreadNum new threads started to parse/process the lines/records * @param queueSize size of queue to save the processing records/lines loaded from source data. Default size is 1024. * @param rowParser * @param onComplete * @throws UncheckedSQLException the unchecked SQL exception * @throws E the e * @throws E2 the e2 */ public static void parse(final Connection conn, final String sql, final long offset, final long count, final int processThreadNum, final int queueSize, final Try.Consumer rowParser, final Try.Runnable onComplete) throws UncheckedSQLException, E, E2 { PreparedStatement stmt = null; try { stmt = prepareStatement(conn, sql); stmt.setFetchDirection(ResultSet.FETCH_FORWARD); stmt.setFetchSize(200); parse(stmt, offset, count, processThreadNum, queueSize, rowParser, onComplete); } catch (SQLException e) { throw new UncheckedSQLException(e); } finally { closeQuietly(stmt); } } /** * * @param * @param stmt * @param rowParser * @throws UncheckedSQLException the unchecked SQL exception * @throws E the e */ public static void parse(final PreparedStatement stmt, final Try.Consumer rowParser) throws UncheckedSQLException, E { parse(stmt, rowParser, Fn.emptyAction()); } /** * * @param * @param * @param stmt * @param rowParser * @param onComplete * @throws UncheckedSQLException the unchecked SQL exception * @throws E the e * @throws E2 the e2 */ public static void parse(final PreparedStatement stmt, final Try.Consumer rowParser, final Try.Runnable onComplete) throws UncheckedSQLException, E, E2 { parse(stmt, 0, Long.MAX_VALUE, rowParser, onComplete); } /** * * @param * @param stmt * @param offset * @param count * @param rowParser * @throws E the e */ public static void parse(final PreparedStatement stmt, final long offset, final long count, final Try.Consumer rowParser) throws E { parse(stmt, offset, count, rowParser, Fn.emptyAction()); } /** * * @param * @param * @param stmt * @param offset * @param count * @param rowParser * @param onComplete * @throws UncheckedSQLException the unchecked SQL exception * @throws E the e * @throws E2 the e2 */ public static void parse(final PreparedStatement stmt, final long offset, final long count, final Try.Consumer rowParser, final Try.Runnable onComplete) throws UncheckedSQLException, E, E2 { parse(stmt, offset, count, 0, 0, rowParser, onComplete); } /** * * @param * @param stmt * @param offset * @param count * @param processThreadNum * @param queueSize * @param rowParser * @throws UncheckedSQLException the unchecked SQL exception * @throws E the e */ public static void parse(final PreparedStatement stmt, final long offset, final long count, final int processThreadNum, final int queueSize, final Try.Consumer rowParser) throws UncheckedSQLException, E { parse(stmt, offset, count, processThreadNum, queueSize, rowParser, Fn.emptyAction()); } /** * Parse the ResultSet obtained by executing query with the specified PreparedStatement. * * @param * @param * @param stmt * @param offset * @param count * @param processThreadNum new threads started to parse/process the lines/records * @param queueSize size of queue to save the processing records/lines loaded from source data. Default size is 1024. * @param rowParser * @param onComplete * @throws UncheckedSQLException the unchecked SQL exception * @throws E the e * @throws E2 the e2 */ public static void parse(final PreparedStatement stmt, final long offset, final long count, final int processThreadNum, final int queueSize, final Try.Consumer rowParser, final Try.Runnable onComplete) throws UncheckedSQLException, E, E2 { ResultSet rs = null; try { rs = stmt.executeQuery(); parse(rs, offset, count, processThreadNum, queueSize, rowParser, onComplete); } catch (SQLException e) { throw new UncheckedSQLException(e); } finally { closeQuietly(rs); } } /** * * @param * @param rs * @param rowParser * @throws UncheckedSQLException the unchecked SQL exception * @throws E the e */ public static void parse(final ResultSet rs, final Try.Consumer rowParser) throws UncheckedSQLException, E { parse(rs, rowParser, Fn.emptyAction()); } /** * * @param * @param * @param rs * @param rowParser * @param onComplete * @throws UncheckedSQLException the unchecked SQL exception * @throws E the e * @throws E2 the e2 */ public static void parse(final ResultSet rs, final Try.Consumer rowParser, final Try.Runnable onComplete) throws UncheckedSQLException, E, E2 { parse(rs, 0, Long.MAX_VALUE, rowParser, onComplete); } /** * * @param * @param rs * @param offset * @param count * @param rowParser * @throws UncheckedSQLException the unchecked SQL exception * @throws E the e */ public static void parse(final ResultSet rs, long offset, long count, final Try.Consumer rowParser) throws UncheckedSQLException, E { parse(rs, offset, count, rowParser, Fn.emptyAction()); } /** * * @param * @param * @param rs * @param offset * @param count * @param rowParser * @param onComplete * @throws UncheckedSQLException the unchecked SQL exception * @throws E the e * @throws E2 the e2 */ public static void parse(final ResultSet rs, long offset, long count, final Try.Consumer rowParser, final Try.Runnable onComplete) throws UncheckedSQLException, E, E2 { parse(rs, offset, count, 0, 0, rowParser, onComplete); } /** * * @param * @param rs * @param offset * @param count * @param processThreadNum * @param queueSize * @param rowParser * @throws UncheckedSQLException the unchecked SQL exception * @throws E the e */ public static void parse(final ResultSet rs, long offset, long count, final int processThreadNum, final int queueSize, final Try.Consumer rowParser) throws UncheckedSQLException, E { parse(rs, offset, count, processThreadNum, queueSize, rowParser, Fn.emptyAction()); } /** * Parse the ResultSet. * * @param * @param * @param rs * @param offset * @param count * @param processThreadNum new threads started to parse/process the lines/records * @param queueSize size of queue to save the processing records/lines loaded from source data. Default size is 1024. * @param rowParser * @param onComplete * @throws UncheckedSQLException the unchecked SQL exception * @throws E the e * @throws E2 the e2 */ public static void parse(final ResultSet rs, long offset, long count, final int processThreadNum, final int queueSize, final Try.Consumer rowParser, final Try.Runnable onComplete) throws UncheckedSQLException, E, E2 { final Iterator iter = new ObjIterator() { private final JdbcUtil.BiRowMapper biFunc = BiRowMapper.TO_ARRAY; private List columnLabels = null; private boolean hasNext; @Override public boolean hasNext() { if (hasNext == false) { try { hasNext = rs.next(); } catch (SQLException e) { throw new UncheckedSQLException(e); } } return hasNext; } @Override public Object[] next() { if (hasNext() == false) { throw new NoSuchElementException(); } hasNext = false; try { if (columnLabels == null) { columnLabels = JdbcUtil.getColumnLabelList(rs); } return biFunc.apply(rs, columnLabels); } catch (SQLException e) { throw new UncheckedSQLException(e); } } }; Iterables.parse(iter, offset, count, processThreadNum, queueSize, rowParser, onComplete); } /** * * @param sourceConn * @param selectSql * @param targetConn * @param insertSql * @return * @throws UncheckedSQLException the unchecked SQL exception */ public static long copy(final Connection sourceConn, final String selectSql, final Connection targetConn, final String insertSql) throws UncheckedSQLException { return copy(sourceConn, selectSql, 200, 0, Integer.MAX_VALUE, targetConn, insertSql, DEFAULT_STMT_SETTER, 200, 0, false); } /** * * @param sourceConn * @param selectSql * @param fetchSize * @param offset * @param count * @param targetConn * @param insertSql * @param stmtSetter * @param batchSize * @param batchInterval * @param inParallel do the read and write in separated threads. * @return * @throws UncheckedSQLException the unchecked SQL exception */ public static long copy(final Connection sourceConn, final String selectSql, final int fetchSize, final long offset, final long count, final Connection targetConn, final String insertSql, final JdbcUtil.BiParametersSetter stmtSetter, final int batchSize, final int batchInterval, final boolean inParallel) throws UncheckedSQLException { PreparedStatement selectStmt = null; PreparedStatement insertStmt = null; int result = 0; try { insertStmt = targetConn.prepareStatement(insertSql); selectStmt = sourceConn.prepareStatement(selectSql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); selectStmt.setFetchSize(fetchSize); copy(selectStmt, offset, count, insertStmt, stmtSetter, batchSize, batchInterval, inParallel); } catch (SQLException e) { throw new UncheckedSQLException(e); } finally { closeQuietly(selectStmt); closeQuietly(insertStmt); } return result; } /** * * @param selectStmt * @param insertStmt * @param stmtSetter * @return * @throws UncheckedSQLException the unchecked SQL exception */ public static long copy(final PreparedStatement selectStmt, final PreparedStatement insertStmt, final JdbcUtil.BiParametersSetter stmtSetter) throws UncheckedSQLException { return copy(selectStmt, 0, Integer.MAX_VALUE, insertStmt, stmtSetter, 200, 0, false); } /** * * @param selectStmt * @param offset * @param count * @param insertStmt * @param stmtSetter * @param batchSize * @param batchInterval * @param inParallel do the read and write in separated threads. * @return * @throws UncheckedSQLException the unchecked SQL exception */ public static long copy(final PreparedStatement selectStmt, final long offset, final long count, final PreparedStatement insertStmt, final JdbcUtil.BiParametersSetter stmtSetter, final int batchSize, final int batchInterval, final boolean inParallel) throws UncheckedSQLException { N.checkArgument(offset >= 0 && count >= 0, "'offset'=%s and 'count'=%s can't be negative", offset, count); N.checkArgument(batchSize > 0 && batchInterval >= 0, "'batchSize'=%s must be greater than 0 and 'batchInterval'=%s can't be negative", batchSize, batchInterval); @SuppressWarnings("rawtypes") final JdbcUtil.BiParametersSetter setter = (JdbcUtil.BiParametersSetter) (stmtSetter == null ? DEFAULT_STMT_SETTER : stmtSetter); final AtomicLong result = new AtomicLong(); final Try.Consumer rowParser = new Try.Consumer() { @Override public void accept(Object[] row) { try { setter.accept(insertStmt, row); insertStmt.addBatch(); result.incrementAndGet(); if ((result.longValue() % batchSize) == 0) { insertStmt.executeBatch(); insertStmt.clearBatch(); if (batchInterval > 0) { N.sleep(batchInterval); } } } catch (SQLException e) { throw new UncheckedSQLException(e); } } }; final Try.Runnable onComplete = new Try.Runnable() { @Override public void run() { if ((result.longValue() % batchSize) > 0) { try { insertStmt.executeBatch(); insertStmt.clearBatch(); } catch (SQLException e) { throw new UncheckedSQLException(e); } } } }; parse(selectStmt, offset, count, 0, inParallel ? DEFAULT_QUEUE_SIZE_FOR_ROW_PARSER : 0, rowParser, onComplete); return result.longValue(); } /** * Checks if is table not exists exception. * * @param e * @return true, if is table not exists exception */ static boolean isTableNotExistsException(final Throwable e) { if (e instanceof SQLException) { SQLException sqlException = (SQLException) e; if (sqlException.getSQLState() != null && sqlStateForTableNotExists.contains(sqlException.getSQLState())) { return true; } final String msg = N.defaultIfNull(e.getMessage(), "").toLowerCase(); return N.notNullOrEmpty(msg) && (msg.contains("not exist") || msg.contains("doesn't exist") || msg.contains("not found")); } else if (e instanceof UncheckedSQLException) { UncheckedSQLException sqlException = (UncheckedSQLException) e; if (sqlException.getSQLState() != null && sqlStateForTableNotExists.contains(sqlException.getSQLState())) { return true; } final String msg = N.defaultIfNull(e.getMessage(), "").toLowerCase(); return N.notNullOrEmpty(msg) && (msg.contains("not exist") || msg.contains("doesn't exist") || msg.contains("not found")); } return false; } /** * Checks if is default id prop value. * * @param propValue * @return true, if is default id prop value * @deprecated for internal only. */ @Deprecated @Internal public static boolean isDefaultIdPropValue(final Object propValue) { return (propValue == null) || (propValue instanceof Number && (((Number) propValue).longValue() == 0)); } /** * * @param sqlCmd * @throws UncheckedSQLException */ @Beta static void run(Try.Runnable sqlCmd) throws UncheckedSQLException { try { sqlCmd.run(); } catch (SQLException e) { throw new UncheckedSQLException(e); } } /** * * @param * @param sqlCmd * @return * @throws UncheckedSQLException */ @Beta static R call(Try.Callable sqlCmd) throws UncheckedSQLException { try { return sqlCmd.call(); } catch (SQLException e) { throw new UncheckedSQLException(e); } } /** * The backed {@code PreparedStatement/CallableStatement} will be closed by default * after any execution methods(which will trigger the backed {@code PreparedStatement/CallableStatement} to be executed, for example: get/query/queryForInt/Long/../findFirst/list/execute/...). * except the {@code 'closeAfterExecution'} flag is set to {@code false} by calling {@code #closeAfterExecution(false)}. * *
* Generally, don't cache or reuse the instance of this class, * except the {@code 'closeAfterExecution'} flag is set to {@code false} by calling {@code #closeAfterExecution(false)}. * *
* Remember: parameter/column index in {@code PreparedStatement/ResultSet} starts from 1, not 0. * * @author haiyangl * @param * @param */ static abstract class AbstractPreparedQuery> implements AutoCloseable { final S stmt; boolean isFetchDirectionSet = false; boolean isBatch = false; boolean isCloseAfterExecution = true; boolean isClosed = false; Runnable closeHandler; /** * Instantiates a new abstract prepared query. * * @param stmt */ AbstractPreparedQuery(S stmt) { this.stmt = stmt; } // /** // * It's designed to void try-catch. // * This method should be called immediately after {@code JdbcUtil#prepareCallableQuery/SQLExecutor#prepareQuery}. // * // * @return // */ // public Try tried() { // assertNotClosed(); // // return Try.of((Q) this); // } /** * * @param closeAfterExecution default is {@code true}. * @return */ public Q closeAfterExecution(boolean closeAfterExecution) { assertNotClosed(); this.isCloseAfterExecution = closeAfterExecution; return (Q) this; } /** * * @return */ boolean isCloseAfterExecution() { return isCloseAfterExecution; } /** * * @param closeHandler A task to execute after this {@code Query} is closed * @return */ public Q onClose(final Runnable closeHandler) { checkArgNotNull(closeHandler, "closeHandler"); assertNotClosed(); if (this.closeHandler == null) { this.closeHandler = closeHandler; } else { final Runnable tmp = this.closeHandler; this.closeHandler = () -> { try { tmp.run(); } finally { closeHandler.run(); } }; } return (Q) this; } /** * Sets the null. * * @param parameterIndex starts from 1, not 0. * @param sqlType * @return * @throws SQLException the SQL exception */ public Q setNull(int parameterIndex, int sqlType) throws SQLException { stmt.setNull(parameterIndex, sqlType); return (Q) this; } /** * Sets the null. * * @param parameterIndex starts from 1, not 0. * @param sqlType * @param typeName * @return * @throws SQLException the SQL exception */ public Q setNull(int parameterIndex, int sqlType, String typeName) throws SQLException { stmt.setNull(parameterIndex, sqlType, typeName); return (Q) this; } /** * Sets the boolean. * * @param parameterIndex starts from 1, not 0. * @param x * @return * @throws SQLException the SQL exception */ public Q setBoolean(int parameterIndex, boolean x) throws SQLException { stmt.setBoolean(parameterIndex, x); return (Q) this; } /** * Sets the boolean. * * @param parameterIndex * @param x * @return * @throws SQLException the SQL exception */ public Q setBoolean(int parameterIndex, Boolean x) throws SQLException { stmt.setBoolean(parameterIndex, N.defaultIfNull(x)); return (Q) this; } /** * Sets the byte. * * @param parameterIndex starts from 1, not 0. * @param x * @return * @throws SQLException the SQL exception */ public Q setByte(int parameterIndex, byte x) throws SQLException { stmt.setByte(parameterIndex, x); return (Q) this; } /** * Sets the byte. * * @param parameterIndex * @param x * @return * @throws SQLException the SQL exception */ public Q setByte(int parameterIndex, Byte x) throws SQLException { stmt.setByte(parameterIndex, N.defaultIfNull(x)); return (Q) this; } /** * Sets the short. * * @param parameterIndex starts from 1, not 0. * @param x * @return * @throws SQLException the SQL exception */ public Q setShort(int parameterIndex, short x) throws SQLException { stmt.setShort(parameterIndex, x); return (Q) this; } /** * Sets the short. * * @param parameterIndex * @param x * @return * @throws SQLException the SQL exception */ public Q setShort(int parameterIndex, Short x) throws SQLException { stmt.setShort(parameterIndex, N.defaultIfNull(x)); return (Q) this; } /** * Sets the int. * * @param parameterIndex starts from 1, not 0. * @param x * @return * @throws SQLException the SQL exception */ public Q setInt(int parameterIndex, int x) throws SQLException { stmt.setInt(parameterIndex, x); return (Q) this; } /** * Sets the int. * * @param parameterIndex * @param x * @return * @throws SQLException the SQL exception */ public Q setInt(int parameterIndex, Integer x) throws SQLException { stmt.setInt(parameterIndex, N.defaultIfNull(x)); return (Q) this; } /** * Sets the long. * * @param parameterIndex starts from 1, not 0. * @param x * @return * @throws SQLException the SQL exception */ public Q setLong(int parameterIndex, long x) throws SQLException { stmt.setLong(parameterIndex, x); return (Q) this; } /** * Sets the long. * * @param parameterIndex * @param x * @return * @throws SQLException the SQL exception */ public Q setLong(int parameterIndex, Long x) throws SQLException { stmt.setLong(parameterIndex, N.defaultIfNull(x)); return (Q) this; } /** * Sets the float. * * @param parameterIndex starts from 1, not 0. * @param x * @return * @throws SQLException the SQL exception */ public Q setFloat(int parameterIndex, float x) throws SQLException { stmt.setFloat(parameterIndex, x); return (Q) this; } /** * Sets the float. * * @param parameterIndex * @param x * @return * @throws SQLException the SQL exception */ public Q setFloat(int parameterIndex, Float x) throws SQLException { stmt.setFloat(parameterIndex, N.defaultIfNull(x)); return (Q) this; } /** * Sets the double. * * @param parameterIndex starts from 1, not 0. * @param x * @return * @throws SQLException the SQL exception */ public Q setDouble(int parameterIndex, double x) throws SQLException { stmt.setDouble(parameterIndex, N.defaultIfNull(x)); return (Q) this; } /** * Sets the double. * * @param parameterIndex * @param x * @return * @throws SQLException the SQL exception */ public Q setDouble(int parameterIndex, Double x) throws SQLException { stmt.setDouble(parameterIndex, x); return (Q) this; } /** * Sets the big decimal. * * @param parameterIndex starts from 1, not 0. * @param x * @return * @throws SQLException the SQL exception */ public Q setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException { stmt.setBigDecimal(parameterIndex, x); return (Q) this; } /** * Sets the string. * * @param parameterIndex starts from 1, not 0. * @param x * @return * @throws SQLException the SQL exception */ public Q setString(int parameterIndex, String x) throws SQLException { stmt.setString(parameterIndex, x); return (Q) this; } /** * Sets the date. * * @param parameterIndex starts from 1, not 0. * @param x * @return * @throws SQLException the SQL exception */ public Q setDate(int parameterIndex, java.sql.Date x) throws SQLException { stmt.setDate(parameterIndex, x); return (Q) this; } /** * Sets the date. * * @param parameterIndex starts from 1, not 0. * @param x * @return * @throws SQLException the SQL exception */ public Q setDate(int parameterIndex, java.util.Date x) throws SQLException { stmt.setDate(parameterIndex, x == null ? null : x instanceof java.sql.Date ? (java.sql.Date) x : new java.sql.Date(x.getTime())); return (Q) this; } /** * Sets the time. * * @param parameterIndex starts from 1, not 0. * @param x * @return * @throws SQLException the SQL exception */ public Q setTime(int parameterIndex, java.sql.Time x) throws SQLException { stmt.setTime(parameterIndex, x); return (Q) this; } /** * Sets the time. * * @param parameterIndex starts from 1, not 0. * @param x * @return * @throws SQLException the SQL exception */ public Q setTime(int parameterIndex, java.util.Date x) throws SQLException { stmt.setTime(parameterIndex, x == null ? null : x instanceof java.sql.Time ? (java.sql.Time) x : new java.sql.Time(x.getTime())); return (Q) this; } /** * Sets the timestamp. * * @param parameterIndex starts from 1, not 0. * @param x * @return * @throws SQLException the SQL exception */ public Q setTimestamp(int parameterIndex, java.sql.Timestamp x) throws SQLException { stmt.setTimestamp(parameterIndex, x); return (Q) this; } /** * Sets the timestamp. * * @param parameterIndex starts from 1, not 0. * @param x * @return * @throws SQLException the SQL exception */ public Q setTimestamp(int parameterIndex, java.util.Date x) throws SQLException { stmt.setTimestamp(parameterIndex, x == null ? null : x instanceof java.sql.Timestamp ? (java.sql.Timestamp) x : new java.sql.Timestamp(x.getTime())); return (Q) this; } /** * Sets the bytes. * * @param parameterIndex * @param x * @return * @throws SQLException the SQL exception */ public Q setBytes(int parameterIndex, byte[] x) throws SQLException { stmt.setBytes(parameterIndex, x); return (Q) this; } /** * Sets the ascii stream. * * @param parameterIndex * @param inputStream * @return * @throws SQLException the SQL exception */ public Q setAsciiStream(int parameterIndex, InputStream inputStream) throws SQLException { stmt.setAsciiStream(parameterIndex, inputStream); return (Q) this; } /** * Sets the ascii stream. * * @param parameterIndex * @param inputStream * @param length * @return * @throws SQLException the SQL exception */ public Q setAsciiStream(int parameterIndex, InputStream inputStream, long length) throws SQLException { stmt.setAsciiStream(parameterIndex, inputStream, length); return (Q) this; } /** * Sets the binary stream. * * @param parameterIndex * @param inputStream * @return * @throws SQLException the SQL exception */ public Q setBinaryStream(int parameterIndex, InputStream inputStream) throws SQLException { stmt.setBinaryStream(parameterIndex, inputStream); return (Q) this; } /** * Sets the binary stream. * * @param parameterIndex * @param inputStream * @param length * @return * @throws SQLException the SQL exception */ public Q setBinaryStream(int parameterIndex, InputStream inputStream, long length) throws SQLException { stmt.setBinaryStream(parameterIndex, inputStream, length); return (Q) this; } /** * Sets the character stream. * * @param parameterIndex * @param reader * @return * @throws SQLException the SQL exception */ public Q setCharacterStream(int parameterIndex, Reader reader) throws SQLException { stmt.setCharacterStream(parameterIndex, reader); return (Q) this; } /** * Sets the character stream. * * @param parameterIndex * @param reader * @param length * @return * @throws SQLException the SQL exception */ public Q setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException { stmt.setCharacterStream(parameterIndex, reader, length); return (Q) this; } /** * Sets the N character stream. * * @param parameterIndex * @param reader * @return * @throws SQLException the SQL exception */ public Q setNCharacterStream(int parameterIndex, Reader reader) throws SQLException { stmt.setNCharacterStream(parameterIndex, reader); return (Q) this; } /** * Sets the N character stream. * * @param parameterIndex * @param reader * @param length * @return * @throws SQLException the SQL exception */ public Q setNCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException { stmt.setNCharacterStream(parameterIndex, reader, length); return (Q) this; } /** * Sets the blob. * * @param parameterIndex * @param x * @return * @throws SQLException the SQL exception */ public Q setBlob(int parameterIndex, java.sql.Blob x) throws SQLException { stmt.setBlob(parameterIndex, x); return (Q) this; } /** * Sets the blob. * * @param parameterIndex * @param inputStream * @return * @throws SQLException the SQL exception */ public Q setBlob(int parameterIndex, InputStream inputStream) throws SQLException { stmt.setBlob(parameterIndex, inputStream); return (Q) this; } /** * Sets the blob. * * @param parameterIndex * @param inputStream * @param length * @return * @throws SQLException the SQL exception */ public Q setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException { stmt.setBlob(parameterIndex, inputStream, length); return (Q) this; } /** * Sets the clob. * * @param parameterIndex * @param x * @return * @throws SQLException the SQL exception */ public Q setClob(int parameterIndex, java.sql.Clob x) throws SQLException { stmt.setClob(parameterIndex, x); return (Q) this; } /** * Sets the clob. * * @param parameterIndex * @param reader * @return * @throws SQLException the SQL exception */ public Q setClob(int parameterIndex, Reader reader) throws SQLException { stmt.setClob(parameterIndex, reader); return (Q) this; } /** * Sets the clob. * * @param parameterIndex * @param reader * @param length * @return * @throws SQLException the SQL exception */ public Q setClob(int parameterIndex, Reader reader, long length) throws SQLException { stmt.setClob(parameterIndex, reader, length); return (Q) this; } /** * Sets the N clob. * * @param parameterIndex * @param x * @return * @throws SQLException the SQL exception */ public Q setNClob(int parameterIndex, java.sql.NClob x) throws SQLException { stmt.setNClob(parameterIndex, x); return (Q) this; } /** * Sets the N clob. * * @param parameterIndex * @param reader * @return * @throws SQLException the SQL exception */ public Q setNClob(int parameterIndex, Reader reader) throws SQLException { stmt.setNClob(parameterIndex, reader); return (Q) this; } /** * Sets the N clob. * * @param parameterIndex * @param reader * @param length * @return * @throws SQLException the SQL exception */ public Q setNClob(int parameterIndex, Reader reader, long length) throws SQLException { stmt.setNClob(parameterIndex, reader, length); return (Q) this; } /** * Sets the URL. * * @param parameterIndex * @param x * @return * @throws SQLException the SQL exception */ public Q setURL(int parameterIndex, URL x) throws SQLException { stmt.setURL(parameterIndex, x); return (Q) this; } /** * Sets the array. * * @param parameterIndex * @param x * @return * @throws SQLException the SQL exception */ public Q setArray(int parameterIndex, java.sql.Array x) throws SQLException { stmt.setArray(parameterIndex, x); return (Q) this; } /** * Sets the SQLXML. * * @param parameterIndex * @param x * @return * @throws SQLException the SQL exception */ public Q setSQLXML(int parameterIndex, java.sql.SQLXML x) throws SQLException { stmt.setSQLXML(parameterIndex, x); return (Q) this; } /** * Sets the ref. * * @param parameterIndex * @param x * @return * @throws SQLException the SQL exception */ public Q setRef(int parameterIndex, java.sql.Ref x) throws SQLException { stmt.setRef(parameterIndex, x); return (Q) this; } /** * Sets the row id. * * @param parameterIndex * @param x * @return * @throws SQLException the SQL exception */ public Q setRowId(int parameterIndex, java.sql.RowId x) throws SQLException { stmt.setRowId(parameterIndex, x); return (Q) this; } /** * Sets the object. * * @param parameterIndex starts from 1, not 0. * @param x * @return * @throws SQLException the SQL exception */ public Q setObject(int parameterIndex, Object x) throws SQLException { if (x == null) { stmt.setObject(parameterIndex, x); } else { N.typeOf(x.getClass()).set(stmt, parameterIndex, x); } return (Q) this; } /** * Sets the object. * * @param parameterIndex starts from 1, not 0. * @param x * @param sqlType * @return * @throws SQLException the SQL exception */ public Q setObject(int parameterIndex, Object x, int sqlType) throws SQLException { stmt.setObject(parameterIndex, x, sqlType); return (Q) this; } /** * Sets the object. * * @param parameterIndex starts from 1, not 0. * @param x * @param sqlType * @param scaleOrLength * @return * @throws SQLException the SQL exception */ public Q setObject(int parameterIndex, Object x, int sqlType, int scaleOrLength) throws SQLException { stmt.setObject(parameterIndex, x, sqlType, scaleOrLength); return (Q) this; } /** * Sets the object. * * @param parameterIndex * @param x * @param sqlType * @return * @throws SQLException the SQL exception */ public Q setObject(int parameterIndex, Object x, SQLType sqlType) throws SQLException { stmt.setObject(parameterIndex, x, sqlType); return (Q) this; } /** * Sets the object. * * @param parameterIndex * @param x * @param sqlType * @param scaleOrLength * @return * @throws SQLException the SQL exception */ public Q setObject(int parameterIndex, Object x, SQLType sqlType, int scaleOrLength) throws SQLException { stmt.setObject(parameterIndex, x, sqlType, scaleOrLength); return (Q) this; } public Q setObject(int parameterIndex, Object x, Type type) throws SQLException { type.set(stmt, parameterIndex, x); return (Q) this; } /** * Sets the parameters. * * @param param1 * @param param2 * @return * @throws SQLException the SQL exception */ public Q setParameters(final String param1, final String param2) throws SQLException { stmt.setString(1, param1); stmt.setString(2, param2); return (Q) this; } /** * Sets the parameters. * * @param param1 * @param param2 * @param param3 * @return * @throws SQLException the SQL exception */ public Q setParameters(final String param1, final String param2, final String param3) throws SQLException { stmt.setString(1, param1); stmt.setString(2, param2); stmt.setString(3, param3); return (Q) this; } /** * Sets the parameters. * * @param param1 * @param param2 * @param param3 * @param param4 * @return * @throws SQLException the SQL exception */ public Q setParameters(final String param1, final String param2, final String param3, final String param4) throws SQLException { stmt.setString(1, param1); stmt.setString(2, param2); stmt.setString(3, param3); stmt.setString(4, param4); return (Q) this; } /** * Sets the parameters. * * @param param1 * @param param2 * @param param3 * @param param4 * @param param5 * @return * @throws SQLException the SQL exception */ public Q setParameters(final String param1, final String param2, final String param3, final String param4, final String param5) throws SQLException { stmt.setString(1, param1); stmt.setString(2, param2); stmt.setString(3, param3); stmt.setString(4, param4); stmt.setString(5, param5); return (Q) this; } /** * Sets the parameters. * * @param param1 * @param param2 * @param param3 * @param param4 * @param param5 * @param param6 * @return * @throws SQLException the SQL exception */ public Q setParameters(final String param1, final String param2, final String param3, final String param4, final String param5, final String param6) throws SQLException { stmt.setString(1, param1); stmt.setString(2, param2); stmt.setString(3, param3); stmt.setString(4, param4); stmt.setString(5, param5); stmt.setString(6, param6); return (Q) this; } /** * Sets the parameters. * * @param param1 * @param param2 * @param param3 * @param param4 * @param param5 * @param param6 * @param param7 * @return * @throws SQLException the SQL exception */ public Q setParameters(final String param1, final String param2, final String param3, final String param4, final String param5, final String param6, final String param7) throws SQLException { stmt.setString(1, param1); stmt.setString(2, param2); stmt.setString(3, param3); stmt.setString(4, param4); stmt.setString(5, param5); stmt.setString(6, param6); stmt.setString(7, param7); return (Q) this; } /** * Sets the parameters. * * @param param1 * @param param2 * @return * @throws SQLException the SQL exception */ public Q setParameters(final Object param1, final Object param2) throws SQLException { setObject(1, param1); setObject(2, param2); return (Q) this; } /** * Sets the parameters. * * @param param1 * @param param2 * @param param3 * @return * @throws SQLException the SQL exception */ public Q setParameters(final Object param1, final Object param2, final Object param3) throws SQLException { setObject(1, param1); setObject(2, param2); setObject(3, param3); return (Q) this; } /** * Sets the parameters. * * @param param1 * @param param2 * @param param3 * @param param4 * @return * @throws SQLException the SQL exception */ public Q setParameters(final Object param1, final Object param2, final Object param3, final Object param4) throws SQLException { setObject(1, param1); setObject(2, param2); setObject(3, param3); setObject(4, param4); return (Q) this; } /** * Sets the parameters. * * @param param1 * @param param2 * @param param3 * @param param4 * @param param5 * @return * @throws SQLException the SQL exception */ public Q setParameters(final Object param1, final Object param2, final Object param3, final Object param4, final Object param5) throws SQLException { setObject(1, param1); setObject(2, param2); setObject(3, param3); setObject(4, param4); setObject(5, param5); return (Q) this; } /** * Sets the parameters. * * @param param1 * @param param2 * @param param3 * @param param4 * @param param5 * @param param6 * @return * @throws SQLException the SQL exception */ public Q setParameters(final Object param1, final Object param2, final Object param3, final Object param4, final Object param5, final Object param6) throws SQLException { setObject(1, param1); setObject(2, param2); setObject(3, param3); setObject(4, param4); setObject(5, param5); setObject(6, param6); return (Q) this; } /** * Sets the parameters. * * @param param1 * @param param2 * @param param3 * @param param4 * @param param5 * @param param6 * @param param7 * @return * @throws SQLException the SQL exception */ public Q setParameters(final Object param1, final Object param2, final Object param3, final Object param4, final Object param5, final Object param6, final Object param7) throws SQLException { setObject(1, param1); setObject(2, param2); setObject(3, param3); setObject(4, param4); setObject(5, param5); setObject(6, param6); setObject(7, param7); return (Q) this; } /** * Sets the parameters. * * @param param1 * @param param2 * @param param3 * @param param4 * @param param5 * @param param6 * @param param7 * @param param8 * @return * @throws SQLException the SQL exception */ public Q setParameters(final Object param1, final Object param2, final Object param3, final Object param4, final Object param5, final Object param6, final Object param7, final Object param8) throws SQLException { setObject(1, param1); setObject(2, param2); setObject(3, param3); setObject(4, param4); setObject(5, param5); setObject(6, param6); setObject(7, param7); setObject(8, param8); return (Q) this; } /** * Sets the parameters. * * @param param1 * @param param2 * @param param3 * @param param4 * @param param5 * @param param6 * @param param7 * @param param8 * @param param9 * @return * @throws SQLException the SQL exception */ public Q setParameters(final Object param1, final Object param2, final Object param3, final Object param4, final Object param5, final Object param6, final Object param7, final Object param8, final Object param9) throws SQLException { setObject(1, param1); setObject(2, param2); setObject(3, param3); setObject(4, param4); setObject(5, param5); setObject(6, param6); setObject(7, param7); setObject(8, param8); setObject(9, param9); return (Q) this; } /** * Sets the parameters. * * @param parameters * @return * @throws IllegalArgumentException if specified {@code parameters} or {@code type} is null. * @throws SQLException the SQL exception */ public Q setParameters(final Object[] parameters) throws IllegalArgumentException, SQLException { checkArgNotNull(parameters, "parameters"); int idx = 1; for (Object param : parameters) { setObject(idx++, param); } return (Q) this; } /** * Sets the parameters. * * @param startParameterIndex * @param parameters * @return * @throws IllegalArgumentException if specified {@code parameters} or {@code type} is null. * @throws SQLException the SQL exception */ public Q setParameters(final Collection parameters) throws IllegalArgumentException, SQLException { checkArgNotNull(parameters, "parameters"); int idx = 1; for (Object param : parameters) { setObject(idx++, param); } return (Q) this; } /** * Sets the parameters. * * @param paramSetter * @return * @throws SQLException the SQL exception */ public Q setParameters(final ParametersSetter paramSetter) throws SQLException { checkArgNotNull(paramSetter, "paramSetter"); boolean noException = false; try { paramSetter.accept(stmt); noException = true; } finally { if (noException == false) { close(); } } return (Q) this; } /** * Sets the parameters. * * @param * @param parameters * @param paramSetter * @return * @throws SQLException the SQL exception */ public Q setParameters(final T parameters, final BiParametersSetter paramSetter) throws SQLException { checkArgNotNull(paramSetter, "paramSetter"); boolean noException = false; try { paramSetter.accept(stmt, parameters); noException = true; } finally { if (noException == false) { close(); } } return (Q) this; } /** * Sets the parameters. * * @param parameters * @return * @throws IllegalArgumentException if specified {@code parameters} or {@code type} is null. * @throws SQLException the SQL exception */ public Q settParameters(final int[] parameters) throws IllegalArgumentException, SQLException { return settParameters(1, parameters); } /** * Sets the parameters. * * @param startParameterIndex * @param parameters * @return * @throws IllegalArgumentException if specified {@code parameters} or {@code type} is null. * @throws SQLException the SQL exception */ public Q settParameters(int startParameterIndex, final int[] parameters) throws IllegalArgumentException, SQLException { checkArgNotNull(parameters, "parameters"); for (int param : parameters) { stmt.setInt(startParameterIndex++, param); } return (Q) this; } /** * Sets the parameters. * * @param parameters * @return * @throws IllegalArgumentException if specified {@code parameters} or {@code type} is null. * @throws SQLException the SQL exception */ public Q settParameters(final long[] parameters) throws IllegalArgumentException, SQLException { return settParameters(1, parameters); } /** * Sets the parameters. * * @param startParameterIndex * @param parameters * @return * @throws IllegalArgumentException if specified {@code parameters} or {@code type} is null. * @throws SQLException the SQL exception */ public Q settParameters(int startParameterIndex, final long[] parameters) throws IllegalArgumentException, SQLException { checkArgNotNull(parameters, "parameters"); for (long param : parameters) { stmt.setLong(startParameterIndex++, param); } return (Q) this; } /** * Sets the parameters. * * @param parameters * @return * @throws IllegalArgumentException if specified {@code parameters} or {@code type} is null. * @throws SQLException the SQL exception */ public Q settParameters(final String[] parameters) throws IllegalArgumentException, SQLException { return settParameters(1, parameters); } /** * Sets the parameters. * * @param startParameterIndex * @param parameters * @return * @throws IllegalArgumentException if specified {@code parameters} or {@code type} is null. * @throws SQLException the SQL exception */ public Q settParameters(int startParameterIndex, final String[] parameters) throws IllegalArgumentException, SQLException { checkArgNotNull(parameters, "parameters"); for (String param : parameters) { stmt.setString(startParameterIndex++, param); } return (Q) this; } /** * Sets the parameters. * * @param * @param parameters * @param type * @return * @throws IllegalArgumentException if specified {@code parameters} or {@code type} is null. * @throws SQLException the SQL exception */ public Q settParameters(final T[] parameters, final Class type) throws IllegalArgumentException, SQLException { return settParameters(1, parameters, type); } /** * Sets the parameters. * * @param * @param startParameterIndex * @param parameters * @param type * @return * @throws IllegalArgumentException if specified {@code parameters} or {@code type} is null. * @throws SQLException the SQL exception */ public Q settParameters(int startParameterIndex, final T[] parameters, final Class type) throws IllegalArgumentException, SQLException { checkArgNotNull(parameters, "parameters"); checkArgNotNull(type, "type"); final Type setter = N.typeOf(type); for (T param : parameters) { setter.set(stmt, startParameterIndex++, param); } return (Q) this; } /** * Sets the parameters. * * @param * @param startParameterIndex * @param parameters * @param type * @return * @throws IllegalArgumentException if specified {@code parameters} or {@code type} is null. * @throws SQLException the SQL exception */ public Q settParameters(final Collection parameters, final Class type) throws IllegalArgumentException, SQLException { return settParameters(1, parameters, type); } /** * Sets the parameters. * * @param * @param startParameterIndex * @param parameters * @param type * @return * @throws IllegalArgumentException if specified {@code parameters} or {@code type} is null. * @throws SQLException the SQL exception */ public Q settParameters(int startParameterIndex, final Collection parameters, final Class type) throws IllegalArgumentException, SQLException { checkArgNotNull(parameters, "parameters"); checkArgNotNull(type, "type"); final Type setter = N.typeOf(type); for (T param : parameters) { setter.set(stmt, startParameterIndex++, param); } return (Q) this; } /** * * @param paramSetter * @return * @throws SQLException the SQL exception */ public Q settParameters(ParametersSetter paramSetter) throws SQLException { checkArgNotNull(paramSetter, "paramSetter"); boolean noException = false; try { paramSetter.accept((Q) this); noException = true; } finally { if (noException == false) { close(); } } return (Q) this; } /** * * @param * @param parameter * @param paramSetter * @return * @throws SQLException the SQL exception */ public Q settParameters(final T parameter, BiParametersSetter paramSetter) throws SQLException { checkArgNotNull(paramSetter, "paramSetter"); boolean noException = false; try { paramSetter.accept((Q) this, parameter); noException = true; } finally { if (noException == false) { close(); } } return (Q) this; } // /** // * @param // * @param batchParameters // * @param parametersSetter // * @return // * @throws SQLException the SQL exception // */ // Q setBatchParameters(final Collection batchParameters, BiParametersSetter parametersSetter) throws SQLException { // return setBatchParameters(batchParameters.iterator(), parametersSetter); // } // // /** // * // * @param // * @param batchParameters // * @param parametersSetter // * @return // * @throws SQLException the SQL exception // */ // Q setBatchParameters(final Iterator batchParameters, BiParametersSetter parametersSetter) throws SQLException { // checkArgNotNull(batchParameters, "batchParameters"); // checkArgNotNull(parametersSetter, "parametersSetter"); // // boolean noException = false; // // try { // if (isBatch) { // stmt.clearBatch(); // } // // final Iterator iter = batchParameters; // // while (iter.hasNext()) { // parametersSetter.accept((Q) this, iter.next()); // stmt.addBatch(); // isBatch = true; // } // // noException = true; // } finally { // if (noException == false) { // close(); // } // } // // return (Q) this; // } /** * @param * @param batchParameters * @param parametersSetter * @return * @throws SQLException the SQL exception */ @Beta public Q addBatchParameters(final Collection batchParameters, BiParametersSetter parametersSetter) throws SQLException { checkArgNotNull(batchParameters, "batchParameters"); checkArgNotNull(parametersSetter, "parametersSetter"); return addBatchParameters(batchParameters.iterator(), parametersSetter); } /** * * @param * @param batchParameters * @param parametersSetter * @return * @throws SQLException the SQL exception */ @Beta public Q addBatchParameters(final Iterator batchParameters, BiParametersSetter parametersSetter) throws SQLException { checkArgNotNull(batchParameters, "batchParameters"); checkArgNotNull(parametersSetter, "parametersSetter"); boolean noException = false; try { final Iterator iter = batchParameters; while (iter.hasNext()) { parametersSetter.accept((Q) this, iter.next()); stmt.addBatch(); isBatch = true; } noException = true; } finally { if (noException == false) { close(); } } return (Q) this; } /** * Adds the batch. * * @return * @throws SQLException the SQL exception */ public Q addBatch() throws SQLException { stmt.addBatch(); isBatch = true; return (Q) this; } /** * Sets the fetch direction. * * @param direction one of ResultSet.FETCH_FORWARD, * ResultSet.FETCH_REVERSE, or ResultSet.FETCH_UNKNOWN * @return * @throws SQLException the SQL exception * @see {@link java.sql.Statement#setFetchDirection(int)} */ public Q setFetchDirection(FetchDirection direction) throws SQLException { isFetchDirectionSet = true; stmt.setFetchDirection(direction.intValue); return (Q) this; } /** * Sets the fetch size. * * @param rows * @return * @throws SQLException the SQL exception */ public Q setFetchSize(int rows) throws SQLException { stmt.setFetchSize(rows); return (Q) this; } /** * Sets the max rows. * * @param max * @return * @throws SQLException the SQL exception */ public Q setMaxRows(int max) throws SQLException { stmt.setMaxRows(max); return (Q) this; } /** * Sets the large max rows. * * @param max * @return * @throws SQLException the SQL exception */ public Q setLargeMaxRows(long max) throws SQLException { stmt.setLargeMaxRows(max); return (Q) this; } /** * Sets the max field size. * * @param max * @return * @throws SQLException the SQL exception */ public Q setMaxFieldSize(int max) throws SQLException { stmt.setMaxFieldSize(max); return (Q) this; } /** * Sets the query timeout. * * @param seconds * @return * @throws SQLException the SQL exception */ public Q setQueryTimeout(int seconds) throws SQLException { stmt.setQueryTimeout(seconds); return (Q) this; } /** * Query for boolean. * * @return * @throws SQLException the SQL exception */ public OptionalBoolean queryForBoolean() throws SQLException { assertNotClosed(); try (ResultSet rs = executeQuery()) { return rs.next() ? OptionalBoolean.of(rs.getBoolean(1)) : OptionalBoolean.empty(); } finally { closeAfterExecutionIfAllowed(); } } /** The Constant charType. */ private static final Type charType = TypeFactory.getType(char.class); /** * Query for char. * * @return * @throws SQLException the SQL exception */ public OptionalChar queryForChar() throws SQLException { assertNotClosed(); try (ResultSet rs = executeQuery()) { if (rs.next()) { return OptionalChar.of(charType.get(rs, 1)); } else { return OptionalChar.empty(); } } finally { closeAfterExecutionIfAllowed(); } } /** * Query for byte. * * @return * @throws SQLException the SQL exception */ public OptionalByte queryForByte() throws SQLException { assertNotClosed(); try (ResultSet rs = executeQuery()) { return rs.next() ? OptionalByte.of(rs.getByte(1)) : OptionalByte.empty(); } finally { closeAfterExecutionIfAllowed(); } } /** * Query for short. * * @return * @throws SQLException the SQL exception */ public OptionalShort queryForShort() throws SQLException { assertNotClosed(); try (ResultSet rs = executeQuery()) { return rs.next() ? OptionalShort.of(rs.getShort(1)) : OptionalShort.empty(); } finally { closeAfterExecutionIfAllowed(); } } /** * Query for int. * * @return * @throws SQLException the SQL exception */ public OptionalInt queryForInt() throws SQLException { assertNotClosed(); try (ResultSet rs = executeQuery()) { return rs.next() ? OptionalInt.of(rs.getInt(1)) : OptionalInt.empty(); } finally { closeAfterExecutionIfAllowed(); } } /** * Query for long. * * @return * @throws SQLException the SQL exception */ public OptionalLong queryForLong() throws SQLException { assertNotClosed(); try (ResultSet rs = executeQuery()) { return rs.next() ? OptionalLong.of(rs.getLong(1)) : OptionalLong.empty(); } finally { closeAfterExecutionIfAllowed(); } } /** * Query for float. * * @return * @throws SQLException the SQL exception */ public OptionalFloat queryForFloat() throws SQLException { assertNotClosed(); try (ResultSet rs = executeQuery()) { return rs.next() ? OptionalFloat.of(rs.getFloat(1)) : OptionalFloat.empty(); } finally { closeAfterExecutionIfAllowed(); } } /** * Query for double. * * @return * @throws SQLException the SQL exception */ public OptionalDouble queryForDouble() throws SQLException { assertNotClosed(); try (ResultSet rs = executeQuery()) { return rs.next() ? OptionalDouble.of(rs.getDouble(1)) : OptionalDouble.empty(); } finally { closeAfterExecutionIfAllowed(); } } /** * Query for string. * * @return * @throws SQLException the SQL exception */ public Nullable queryForString() throws SQLException { assertNotClosed(); try (ResultSet rs = executeQuery()) { return rs.next() ? Nullable.of(rs.getString(1)) : Nullable. empty(); } finally { closeAfterExecutionIfAllowed(); } } /** * Query big decimal. * * @return * @throws SQLException the SQL exception */ public Nullable queryBigDecimal() throws SQLException { assertNotClosed(); try (ResultSet rs = executeQuery()) { return rs.next() ? Nullable.of(rs.getBigDecimal(1)) : Nullable. empty(); } finally { closeAfterExecutionIfAllowed(); } } /** * Query for date. * * @return * @throws SQLException the SQL exception */ public Nullable queryForDate() throws SQLException { assertNotClosed(); try (ResultSet rs = executeQuery()) { return rs.next() ? Nullable.of(rs.getDate(1)) : Nullable. empty(); } finally { closeAfterExecutionIfAllowed(); } } /** * Query for time. * * @return * @throws SQLException the SQL exception */ public Nullable queryForTime() throws SQLException { assertNotClosed(); try (ResultSet rs = executeQuery()) { return rs.next() ? Nullable.of(rs.getTime(1)) : Nullable. empty(); } finally { closeAfterExecutionIfAllowed(); } } /** * Query for timestamp. * * @return * @throws SQLException the SQL exception */ public Nullable queryForTimestamp() throws SQLException { assertNotClosed(); try (ResultSet rs = executeQuery()) { return rs.next() ? Nullable.of(rs.getTimestamp(1)) : Nullable. empty(); } finally { closeAfterExecutionIfAllowed(); } } /** * Returns a {@code Nullable} describing the value in the first row/column if it exists, otherwise return an empty {@code Nullable}. * * @param the value type * @param targetClass * @return * @throws SQLException the SQL exception */ public Nullable queryForSingleResult(Class targetClass) throws SQLException { checkArgNotNull(targetClass, "targetClass"); assertNotClosed(); try (ResultSet rs = executeQuery()) { return rs.next() ? Nullable.of(N.convert(JdbcUtil.getColumnValue(rs, 1), targetClass)) : Nullable. empty(); } finally { closeAfterExecutionIfAllowed(); } } /** * Returns an {@code Optional} describing the value in the first row/column if it exists, otherwise return an empty {@code Optional}. * * @param the value type * @param targetClass * @return * @throws SQLException the SQL exception */ public Optional queryForSingleNonNull(Class targetClass) throws SQLException { checkArgNotNull(targetClass, "targetClass"); assertNotClosed(); try (ResultSet rs = executeQuery()) { return rs.next() ? Optional.of(N.convert(JdbcUtil.getColumnValue(rs, 1), targetClass)) : Optional. empty(); } finally { closeAfterExecutionIfAllowed(); } } /** * Returns a {@code Nullable} describing the value in the first row/column if it exists, otherwise return an empty {@code Nullable}. * And throws {@code DuplicatedResultException} if more than one record found. * * @param the value type * @param targetClass * @return * @throws DuplicatedResultException if more than one record found. * @throws SQLException the SQL exception */ public Nullable queryForUniqueResult(Class targetClass) throws DuplicatedResultException, SQLException { checkArgNotNull(targetClass, "targetClass"); assertNotClosed(); try (ResultSet rs = executeQuery()) { final Nullable result = rs.next() ? Nullable.of(N.convert(JdbcUtil.getColumnValue(rs, 1), targetClass)) : Nullable. empty(); if (result.isPresent() && rs.next()) { throw new DuplicatedResultException( "At least two results found: " + Strings.concat(result.get(), ", ", N.convert(JdbcUtil.getColumnValue(rs, 1), targetClass))); } return result; } finally { closeAfterExecutionIfAllowed(); } } /** * Returns an {@code Optional} describing the value in the first row/column if it exists, otherwise return an empty {@code Optional}. * And throws {@code DuplicatedResultException} if more than one record found. * * @param the value type * @param targetClass * @return * @throws DuplicatedResultException if more than one record found. * @throws SQLException the SQL exception */ public Optional queryForUniqueNonNull(Class targetClass) throws DuplicatedResultException, SQLException { checkArgNotNull(targetClass, "targetClass"); assertNotClosed(); try (ResultSet rs = executeQuery()) { final Optional result = rs.next() ? Optional.of(N.convert(JdbcUtil.getColumnValue(rs, 1), targetClass)) : Optional. empty(); if (result.isPresent() && rs.next()) { throw new DuplicatedResultException( "At least two results found: " + Strings.concat(result.get(), ", ", N.convert(JdbcUtil.getColumnValue(rs, 1), targetClass))); } return result; } finally { closeAfterExecutionIfAllowed(); } } /** * * @param * @param targetClass * @param rs * @return * @throws SQLException the SQL exception */ private T get(Class targetClass, ResultSet rs) throws SQLException { final List columnLabels = JdbcUtil.getColumnLabelList(rs); return BiRowMapper.to(targetClass).apply(rs, columnLabels); } /** * * @return * @throws SQLException the SQL exception */ public DataSet query() throws SQLException { return query(ResultExtractor.TO_DATA_SET); } /** * * @param * @param resultExtrator * @return * @throws SQLException the SQL exception */ public R query(final ResultExtractor resultExtrator) throws SQLException { checkArgNotNull(resultExtrator, "resultExtrator"); assertNotClosed(); try (ResultSet rs = executeQuery()) { return checkNotResultSet(resultExtrator.apply(rs)); } finally { closeAfterExecutionIfAllowed(); } } /** * * @param * @param resultExtrator * @return * @throws SQLException the SQL exception */ public R query(final BiResultExtractor resultExtrator) throws SQLException { checkArgNotNull(resultExtrator, "resultExtrator"); assertNotClosed(); try (ResultSet rs = executeQuery()) { return checkNotResultSet(resultExtrator.apply(rs, getColumnLabelList(rs))); } finally { closeAfterExecutionIfAllowed(); } } /** * * @param * @param targetClass * @return * @throws DuplicatedResultException If there are more than one record found by the query * @throws SQLException the SQL exception */ public Optional get(final Class targetClass) throws DuplicatedResultException, SQLException { return Optional.ofNullable(gett(targetClass)); } /** * * @param * @param rowMapper * @return * @throws DuplicatedResultException If there are more than one record found by the query * @throws SQLException the SQL exception */ public Optional get(RowMapper rowMapper) throws DuplicatedResultException, SQLException { return Optional.ofNullable(gett(rowMapper)); } /** * * @param * @param rowMapper * @return * @throws DuplicatedResultException If there are more than one record found by the query * @throws SQLException the SQL exception */ public Optional get(BiRowMapper rowMapper) throws DuplicatedResultException, SQLException { return Optional.ofNullable(gett(rowMapper)); } /** * Gets the t. * * @param * @param targetClass * @return * @throws DuplicatedResultException If there are more than one record found by the query * @throws SQLException the SQL exception */ public T gett(final Class targetClass) throws DuplicatedResultException, SQLException { checkArgNotNull(targetClass, "targetClass"); assertNotClosed(); try (ResultSet rs = executeQuery()) { if (rs.next()) { final T result = Objects.requireNonNull(get(targetClass, rs)); if (rs.next()) { throw new DuplicatedResultException("There are more than one record found by the query"); } return result; } else { return null; } } finally { closeAfterExecutionIfAllowed(); } } /** * Gets the t. * * @param * @param rowMapper * @return * @throws DuplicatedResultException If there are more than one record found by the query * @throws SQLException the SQL exception */ public T gett(RowMapper rowMapper) throws DuplicatedResultException, SQLException { checkArgNotNull(rowMapper, "rowMapper"); assertNotClosed(); try (ResultSet rs = executeQuery()) { if (rs.next()) { final T result = Objects.requireNonNull(rowMapper.apply(rs)); if (rs.next()) { throw new DuplicatedResultException("There are more than one record found by the query"); } return result; } else { return null; } } finally { closeAfterExecutionIfAllowed(); } } /** * Gets the t. * * @param * @param rowMapper * @return * @throws DuplicatedResultException If there are more than one record found by the query * @throws SQLException the SQL exception */ public T gett(BiRowMapper rowMapper) throws DuplicatedResultException, SQLException { checkArgNotNull(rowMapper, "rowMapper"); assertNotClosed(); try (ResultSet rs = executeQuery()) { if (rs.next()) { final T result = Objects.requireNonNull(rowMapper.apply(rs, JdbcUtil.getColumnLabelList(rs))); if (rs.next()) { throw new DuplicatedResultException("There are more than one record found by the query"); } return result; } else { return null; } } finally { closeAfterExecutionIfAllowed(); } } /** * * @param * @param targetClass * @return * @throws SQLException the SQL exception */ public Optional findFirst(final Class targetClass) throws SQLException { checkArgNotNull(targetClass, "targetClass"); assertNotClosed(); try (ResultSet rs = executeQuery()) { if (rs.next()) { return Optional.of(get(targetClass, rs)); } else { return Optional.empty(); } } finally { closeAfterExecutionIfAllowed(); } } /** * * @param * @param rowMapper * @return * @throws SQLException the SQL exception */ public Optional findFirst(RowMapper rowMapper) throws SQLException { checkArgNotNull(rowMapper, "rowMapper"); assertNotClosed(); try (ResultSet rs = executeQuery()) { return rs.next() ? Optional.of(rowMapper.apply(rs)) : Optional. empty(); } finally { closeAfterExecutionIfAllowed(); } } /** * * @param * @param rowFilter * @param rowMapper * @return * @throws SQLException the SQL exception */ public Optional findFirst(final RowFilter rowFilter, RowMapper rowMapper) throws SQLException { checkArgNotNull(rowFilter, "rowFilter"); checkArgNotNull(rowMapper, "rowMapper"); assertNotClosed(); try (ResultSet rs = executeQuery()) { while (rs.next()) { if (rowFilter.test(rs)) { return Optional.of(rowMapper.apply(rs)); } } return Optional.empty(); } finally { closeAfterExecutionIfAllowed(); } } /** * * @param * @param rowMapper * @return * @throws SQLException the SQL exception */ public Optional findFirst(BiRowMapper rowMapper) throws SQLException { checkArgNotNull(rowMapper, "rowMapper"); assertNotClosed(); try (ResultSet rs = executeQuery()) { return rs.next() ? Optional.of(rowMapper.apply(rs, JdbcUtil.getColumnLabelList(rs))) : Optional. empty(); } finally { closeAfterExecutionIfAllowed(); } } /** * * @param * @param rowFilter * @param rowMapper * @return * @throws SQLException the SQL exception */ public Optional findFirst(final BiRowFilter rowFilter, BiRowMapper rowMapper) throws SQLException { checkArgNotNull(rowFilter, "rowFilter"); checkArgNotNull(rowMapper, "rowMapper"); assertNotClosed(); try (ResultSet rs = executeQuery()) { final List columnLabels = JdbcUtil.getColumnLabelList(rs); while (rs.next()) { if (rowFilter.test(rs, columnLabels)) { return Optional.of(rowMapper.apply(rs, columnLabels)); } } return Optional.empty(); } finally { closeAfterExecutionIfAllowed(); } } /** * * @param * @param targetClass * @return * @throws SQLException the SQL exception */ public List list(final Class targetClass) throws SQLException { return list(BiRowMapper.to(targetClass)); } /** * * @param * @param targetClass * @param maxResult * @return * @throws SQLException the SQL exception * @deprecated the result size should be limited in database server side by sql scripts. */ @Deprecated public List list(final Class targetClass, int maxResult) throws SQLException { return list(BiRowMapper.to(targetClass), maxResult); } /** * * @param * @param rowMapper * @return * @throws SQLException the SQL exception */ public List list(RowMapper rowMapper) throws SQLException { return list(rowMapper, Integer.MAX_VALUE); } /** * * @param * @param rowMapper * @param maxResult * @return * @throws SQLException the SQL exception * @deprecated the result size should be limited in database server side by sql scripts. */ @Deprecated public List list(RowMapper rowMapper, int maxResult) throws SQLException { return list(RowFilter.ALWAYS_TRUE, rowMapper, maxResult); } /** * * @param * @param rowFilter * @param rowMapper * @return * @throws SQLException the SQL exception */ public List list(final RowFilter rowFilter, RowMapper rowMapper) throws SQLException { return list(rowFilter, rowMapper, Integer.MAX_VALUE); } /** * * @param * @param rowFilter * @param rowMapper * @param maxResult * @return * @throws SQLException the SQL exception */ public List list(final RowFilter rowFilter, RowMapper rowMapper, int maxResult) throws SQLException { checkArgNotNull(rowFilter, "rowFilter"); checkArgNotNull(rowMapper, "rowMapper"); checkArg(maxResult >= 0, "'maxResult' can' be negative: " + maxResult); assertNotClosed(); try (ResultSet rs = executeQuery()) { final List result = new ArrayList<>(); while (maxResult > 0 && rs.next()) { if (rowFilter.test(rs)) { result.add(rowMapper.apply(rs)); maxResult--; } } return result; } finally { closeAfterExecutionIfAllowed(); } } /** * * @param * @param rowMapper * @return * @throws SQLException the SQL exception */ public List list(BiRowMapper rowMapper) throws SQLException { return list(rowMapper, Integer.MAX_VALUE); } /** * * @param * @param rowMapper * @param maxResult * @return * @throws SQLException the SQL exception * @deprecated the result size should be limited in database server side by sql scripts. */ @Deprecated public List list(BiRowMapper rowMapper, int maxResult) throws SQLException { return list(BiRowFilter.ALWAYS_TRUE, rowMapper, maxResult); } /** * * @param * @param rowFilter * @param rowMapper * @return * @throws SQLException the SQL exception */ public List list(final BiRowFilter rowFilter, BiRowMapper rowMapper) throws SQLException { return list(rowFilter, rowMapper, Integer.MAX_VALUE); } /** * * @param * @param rowFilter * @param rowMapper * @param maxResult * @return * @throws SQLException the SQL exception */ public List list(final BiRowFilter rowFilter, BiRowMapper rowMapper, int maxResult) throws SQLException { checkArgNotNull(rowFilter, "rowFilter"); checkArgNotNull(rowMapper, "rowMapper"); checkArg(maxResult >= 0, "'maxResult' can' be negative: " + maxResult); assertNotClosed(); try (ResultSet rs = executeQuery()) { final List columnLabels = JdbcUtil.getColumnLabelList(rs); final List result = new ArrayList<>(); while (maxResult > 0 && rs.next()) { if (rowFilter.test(rs, columnLabels)) { result.add(rowMapper.apply(rs, columnLabels)); maxResult--; } } return result; } finally { closeAfterExecutionIfAllowed(); } } /** * lazy-execution, lazy-fetch. * * @param * @param targetClass * @return * @throws SQLException the SQL exception */ public ExceptionalStream stream(final Class targetClass) throws SQLException { return stream(BiRowMapper.to(targetClass)); } /** * lazy-execution, lazy-fetch. * * @param * @param rowMapper * @return * @throws SQLException the SQL exception */ public ExceptionalStream stream(final RowMapper rowMapper) throws SQLException { checkArgNotNull(rowMapper, "rowMapper"); assertNotClosed(); final ExceptionalIterator lazyIter = ExceptionalIterator .of(new Try.Supplier, SQLException>() { private ExceptionalIterator internalIter; @Override public ExceptionalIterator get() throws SQLException { if (internalIter == null) { ResultSet rs = null; try { rs = executeQuery(); final ResultSet resultSet = rs; internalIter = new ExceptionalIterator() { private boolean hasNext; @Override public boolean hasNext() throws SQLException { if (hasNext == false) { hasNext = resultSet.next(); } return hasNext; } @Override public T next() throws SQLException { if (hasNext() == false) { throw new NoSuchElementException(); } hasNext = false; return rowMapper.apply(resultSet); } @Override public void skip(long n) throws SQLException { N.checkArgNotNegative(n, "n"); final long m = hasNext ? n - 1 : n; hasNext = false; JdbcUtil.skip(resultSet, m); } @Override public long count() throws SQLException { long cnt = hasNext ? 1 : 0; hasNext = false; while (resultSet.next()) { cnt++; } return cnt; } @Override public void close() throws SQLException { try { JdbcUtil.closeQuietly(resultSet); } finally { closeAfterExecutionIfAllowed(); } } }; } finally { if (internalIter == null) { try { JdbcUtil.closeQuietly(rs); } finally { closeAfterExecutionIfAllowed(); } } } } return internalIter; } }); return ExceptionalStream.newStream(lazyIter).onClose(new Try.Runnable() { @Override public void run() throws SQLException { lazyIter.close(); } }); } /** * lazy-execution, lazy-fetch. * * @param * @param rowMapper * @return * @throws SQLException the SQL exception */ public ExceptionalStream stream(final BiRowMapper rowMapper) throws SQLException { checkArgNotNull(rowMapper, "rowMapper"); assertNotClosed(); final ExceptionalIterator lazyIter = ExceptionalIterator .of(new Try.Supplier, SQLException>() { private ExceptionalIterator internalIter; @Override public ExceptionalIterator get() throws SQLException { if (internalIter == null) { ResultSet rs = null; try { rs = executeQuery(); final ResultSet resultSet = rs; internalIter = new ExceptionalIterator() { private List columnLabels = null; private boolean hasNext; @Override public boolean hasNext() throws SQLException { if (hasNext == false) { hasNext = resultSet.next(); } return hasNext; } @Override public T next() throws SQLException { if (hasNext() == false) { throw new NoSuchElementException(); } hasNext = false; if (columnLabels == null) { columnLabels = JdbcUtil.getColumnLabelList(resultSet); } return rowMapper.apply(resultSet, columnLabels); } @Override public void skip(long n) throws SQLException { N.checkArgNotNegative(n, "n"); final long m = hasNext ? n - 1 : n; hasNext = false; JdbcUtil.skip(resultSet, m); } @Override public long count() throws SQLException { long cnt = hasNext ? 1 : 0; hasNext = false; while (resultSet.next()) { cnt++; } return cnt; } @Override public void close() throws SQLException { try { JdbcUtil.closeQuietly(resultSet); } finally { closeAfterExecutionIfAllowed(); } } }; } finally { if (internalIter == null) { try { JdbcUtil.closeQuietly(rs); } finally { closeAfterExecutionIfAllowed(); } } } } return internalIter; } }); return ExceptionalStream.newStream(lazyIter).onClose(new Try.Runnable() { @Override public void run() throws SQLException { lazyIter.close(); } }); } /** * lazy-execution, lazy-fetch. * * @param * @param rowFilter * @param rowMapper * @return * @throws SQLException */ public ExceptionalStream stream(final RowFilter rowFilter, final RowMapper rowMapper) throws SQLException { checkArgNotNull(rowFilter, "rowFilter"); checkArgNotNull(rowMapper, "rowMapper"); assertNotClosed(); final ExceptionalIterator lazyIter = ExceptionalIterator .of(new Try.Supplier, SQLException>() { private ExceptionalIterator internalIter; @Override public ExceptionalIterator get() throws SQLException { if (internalIter == null) { ResultSet rs = null; try { rs = executeQuery(); final ResultSet resultSet = rs; internalIter = new ExceptionalIterator() { private boolean hasNext; @Override public boolean hasNext() throws SQLException { if (hasNext == false) { while (resultSet.next()) { if (rowFilter.test(resultSet)) { hasNext = true; break; } } } return hasNext; } @Override public T next() throws SQLException { if (hasNext() == false) { throw new NoSuchElementException(); } hasNext = false; return rowMapper.apply(resultSet); } @Override public void close() throws SQLException { try { JdbcUtil.closeQuietly(resultSet); } finally { closeAfterExecutionIfAllowed(); } } }; } finally { if (internalIter == null) { try { JdbcUtil.closeQuietly(rs); } finally { closeAfterExecutionIfAllowed(); } } } } return internalIter; } }); return ExceptionalStream.newStream(lazyIter).onClose(new Try.Runnable() { @Override public void run() throws SQLException { lazyIter.close(); } }); } /** * lazy-execution, lazy-fetch. * * @param * @param rowFilter * @param rowMapper * @return * @throws SQLException the SQL exception */ public ExceptionalStream stream(final BiRowFilter rowFilter, final BiRowMapper rowMapper) throws SQLException { checkArgNotNull(rowFilter, "rowFilter"); checkArgNotNull(rowMapper, "rowMapper"); assertNotClosed(); final ExceptionalIterator lazyIter = ExceptionalIterator .of(new Try.Supplier, SQLException>() { private ExceptionalIterator internalIter; @Override public ExceptionalIterator get() throws SQLException { if (internalIter == null) { ResultSet rs = null; try { rs = executeQuery(); final ResultSet resultSet = rs; internalIter = new ExceptionalIterator() { private List columnLabels = null; private boolean hasNext; @Override public boolean hasNext() throws SQLException { if (columnLabels == null) { columnLabels = JdbcUtil.getColumnLabelList(resultSet); } if (hasNext == false) { while (resultSet.next()) { if (rowFilter.test(resultSet, columnLabels)) { hasNext = true; break; } } } return hasNext; } @Override public T next() throws SQLException { if (hasNext() == false) { throw new NoSuchElementException(); } hasNext = false; return rowMapper.apply(resultSet, columnLabels); } @Override public void close() throws SQLException { try { JdbcUtil.closeQuietly(resultSet); } finally { closeAfterExecutionIfAllowed(); } } }; } finally { if (internalIter == null) { try { JdbcUtil.closeQuietly(rs); } finally { closeAfterExecutionIfAllowed(); } } } } return internalIter; } }); return ExceptionalStream.newStream(lazyIter).onClose(new Try.Runnable() { @Override public void run() throws SQLException { lazyIter.close(); } }); } /** * Note: using {@code select 1 from ...}, not {@code select count(*) from ...}. * * @return true, if successful * @throws SQLException the SQL exception */ public boolean exists() throws SQLException { assertNotClosed(); try (ResultSet rs = executeQuery()) { return rs.next(); } finally { closeAfterExecutionIfAllowed(); } } /** * * @param rowConsumer * @throws SQLException the SQL exception */ public void ifExists(final RowConsumer rowConsumer) throws SQLException { checkArgNotNull(rowConsumer, "rowConsumer"); assertNotClosed(); try (ResultSet rs = executeQuery()) { if (rs.next()) { rowConsumer.accept(rs); } } finally { closeAfterExecutionIfAllowed(); } } /** * * @param rowConsumer * @throws SQLException the SQL exception */ public void ifExists(final BiRowConsumer rowConsumer) throws SQLException { checkArgNotNull(rowConsumer, "rowConsumer"); assertNotClosed(); try (ResultSet rs = executeQuery()) { if (rs.next()) { rowConsumer.accept(rs, JdbcUtil.getColumnLabelList(rs)); } } finally { closeAfterExecutionIfAllowed(); } } /** * If exists or else. * * @param rowConsumer * @param orElseAction * @throws SQLException the SQL exception */ public void ifExistsOrElse(final RowConsumer rowConsumer, Try.Runnable orElseAction) throws SQLException { checkArgNotNull(rowConsumer, "rowConsumer"); checkArgNotNull(orElseAction, "orElseAction"); assertNotClosed(); try (ResultSet rs = executeQuery()) { if (rs.next()) { rowConsumer.accept(rs); } else { orElseAction.run(); } } finally { closeAfterExecutionIfAllowed(); } } /** * If exists or else. * * @param rowConsumer * @param orElseAction * @throws SQLException the SQL exception */ public void ifExistsOrElse(final BiRowConsumer rowConsumer, Try.Runnable orElseAction) throws SQLException { checkArgNotNull(rowConsumer, "rowConsumer"); checkArgNotNull(orElseAction, "orElseAction"); assertNotClosed(); try (ResultSet rs = executeQuery()) { if (rs.next()) { rowConsumer.accept(rs, JdbcUtil.getColumnLabelList(rs)); } else { orElseAction.run(); } } finally { closeAfterExecutionIfAllowed(); } } /** * Note: using {@code select count(*) from ...} * * @return * @throws SQLException the SQL exception * @deprecated may be misused and it's inefficient. */ @Deprecated public int count() throws SQLException { assertNotClosed(); try (ResultSet rs = executeQuery()) { int cnt = 0; while (rs.next()) { cnt++; } return cnt; } finally { closeAfterExecutionIfAllowed(); } } /** * * @param rowFilter * @return * @throws SQLException the SQL exception */ public int count(final RowFilter rowFilter) throws SQLException { checkArgNotNull(rowFilter, "rowFilter"); assertNotClosed(); try (ResultSet rs = executeQuery()) { int cnt = 0; while (rs.next()) { if (rowFilter.test(rs)) { cnt++; } } return cnt; } finally { closeAfterExecutionIfAllowed(); } } /** * * @param rowFilter * @return * @throws SQLException the SQL exception */ public int count(final BiRowFilter rowFilter) throws SQLException { checkArgNotNull(rowFilter, "rowFilter"); assertNotClosed(); try (ResultSet rs = executeQuery()) { final List columnLabels = JdbcUtil.getColumnLabelList(rs); int cnt = 0; while (rs.next()) { if (rowFilter.test(rs, columnLabels)) { cnt++; } } return cnt; } finally { closeAfterExecutionIfAllowed(); } } /** * * @param rowFilter * @return true, if successful * @throws SQLException the SQL exception */ public boolean anyMatch(final RowFilter rowFilter) throws SQLException { checkArgNotNull(rowFilter, "rowFilter"); assertNotClosed(); try (ResultSet rs = executeQuery()) { while (rs.next()) { if (rowFilter.test(rs)) { return true; } } return false; } finally { closeAfterExecutionIfAllowed(); } } /** * * @param rowFilter * @return true, if successful * @throws SQLException the SQL exception */ public boolean anyMatch(final BiRowFilter rowFilter) throws SQLException { checkArgNotNull(rowFilter, "rowFilter"); assertNotClosed(); try (ResultSet rs = executeQuery()) { final List columnLabels = JdbcUtil.getColumnLabelList(rs); while (rs.next()) { if (rowFilter.test(rs, columnLabels)) { return true; } } return false; } finally { closeAfterExecutionIfAllowed(); } } /** * * @param rowFilter * @return true, if successful * @throws SQLException the SQL exception */ public boolean allMatch(final RowFilter rowFilter) throws SQLException { checkArgNotNull(rowFilter, "rowFilter"); assertNotClosed(); try (ResultSet rs = executeQuery()) { while (rs.next()) { if (rowFilter.test(rs) == false) { return false; } } return true; } finally { closeAfterExecutionIfAllowed(); } } /** * * @param rowFilter * @return true, if successful * @throws SQLException the SQL exception */ public boolean allMatch(final BiRowFilter rowFilter) throws SQLException { checkArgNotNull(rowFilter, "rowFilter"); assertNotClosed(); try (ResultSet rs = executeQuery()) { final List columnLabels = JdbcUtil.getColumnLabelList(rs); while (rs.next()) { if (rowFilter.test(rs, columnLabels) == false) { return false; } } return true; } finally { closeAfterExecutionIfAllowed(); } } /** * * @param rowFilter * @return true, if successful * @throws SQLException the SQL exception */ public boolean noneMatch(final RowFilter rowFilter) throws SQLException { return anyMatch(rowFilter) == false; } /** * * @param rowFilter * @return true, if successful * @throws SQLException the SQL exception */ public boolean noneMatch(final BiRowFilter rowFilter) throws SQLException { return anyMatch(rowFilter) == false; } /** * * @param rowConsumer * @throws SQLException the SQL exception */ public void forEach(final RowConsumer rowConsumer) throws SQLException { checkArgNotNull(rowConsumer, "rowConsumer"); assertNotClosed(); try (ResultSet rs = executeQuery()) { while (rs.next()) { rowConsumer.accept(rs); } } finally { closeAfterExecutionIfAllowed(); } } /** * * @param rowFilter * @param rowConsumer * @throws SQLException the SQL exception */ public void forEach(final RowFilter rowFilter, final RowConsumer rowConsumer) throws SQLException { checkArgNotNull(rowFilter, "rowFilter"); checkArgNotNull(rowConsumer, "rowConsumer"); assertNotClosed(); try (ResultSet rs = executeQuery()) { while (rs.next()) { if (rowFilter.test(rs)) { rowConsumer.accept(rs); } } } finally { closeAfterExecutionIfAllowed(); } } /** * * @param rowConsumer * @throws SQLException the SQL exception */ public void forEach(final BiRowConsumer rowConsumer) throws SQLException { checkArgNotNull(rowConsumer, "rowConsumer"); assertNotClosed(); try (ResultSet rs = executeQuery()) { final List columnLabels = JdbcUtil.getColumnLabelList(rs); while (rs.next()) { rowConsumer.accept(rs, columnLabels); } } finally { closeAfterExecutionIfAllowed(); } } /** * * @param rowFilter * @param rowConsumer * @throws SQLException the SQL exception */ public void forEach(final BiRowFilter rowFilter, final BiRowConsumer rowConsumer) throws SQLException { checkArgNotNull(rowFilter, "rowFilter"); checkArgNotNull(rowConsumer, "rowConsumer"); assertNotClosed(); try (ResultSet rs = executeQuery()) { final List columnLabels = JdbcUtil.getColumnLabelList(rs); while (rs.next()) { if (rowFilter.test(rs, columnLabels)) { rowConsumer.accept(rs, columnLabels); } } } finally { closeAfterExecutionIfAllowed(); } } /** * * @return * @throws SQLException the SQL exception */ private ResultSet executeQuery() throws SQLException { if (!isFetchDirectionSet) { stmt.setFetchDirection(ResultSet.FETCH_FORWARD); } return stmt.executeQuery(); } /** * Returns the generated key if it exists. * * @param * @return * @throws SQLException the SQL exception */ public Optional insert() throws SQLException { return insert((RowMapper) SINGLE_GENERATED_KEY_EXTRACTOR); } /** * * @param * @param autoGeneratedKeyExtractor * @return * @throws SQLException the SQL exception */ public Optional insert(final RowMapper autoGeneratedKeyExtractor) throws SQLException { assertNotClosed(); try { stmt.executeUpdate(); try (ResultSet rs = stmt.getGeneratedKeys()) { return rs.next() ? Optional.ofNullable(autoGeneratedKeyExtractor.apply(rs)) : Optional. empty(); } } finally { closeAfterExecutionIfAllowed(); } } /** * * @param * @param autoGeneratedKeyExtractor * @return * @throws SQLException the SQL exception */ public Optional insert(final BiRowMapper autoGeneratedKeyExtractor) throws SQLException { assertNotClosed(); try { stmt.executeUpdate(); try (ResultSet rs = stmt.getGeneratedKeys()) { if (rs.next()) { final List columnLabels = JdbcUtil.getColumnLabelList(rs); return Optional.ofNullable(autoGeneratedKeyExtractor.apply(rs, columnLabels)); } else { return Optional. empty(); } } } finally { closeAfterExecutionIfAllowed(); } } /** * Returns the generated key if it exists. * * @param * @return * @throws SQLException the SQL exception */ public List batchInsert() throws SQLException { return batchInsert((RowMapper) SINGLE_GENERATED_KEY_EXTRACTOR); } /** * * @param * @param autoGeneratedKeyExtractor * @return * @throws SQLException the SQL exception */ public List batchInsert(final RowMapper autoGeneratedKeyExtractor) throws SQLException { assertNotClosed(); try { stmt.executeBatch(); List ids = new ArrayList<>(); try (ResultSet rs = stmt.getGeneratedKeys()) { while (rs.next()) { ids.add(autoGeneratedKeyExtractor.apply(rs)); } if (N.notNullOrEmpty(ids) && Stream.of(ids).allMatch(Fn.isNull())) { ids = new ArrayList<>(); } return ids; } finally { stmt.clearBatch(); } } finally { closeAfterExecutionIfAllowed(); } } /** * * @param * @param autoGeneratedKeyExtractor * @return * @throws SQLException the SQL exception */ public List batchInsert(final BiRowMapper autoGeneratedKeyExtractor) throws SQLException { assertNotClosed(); try { stmt.executeBatch(); List ids = new ArrayList<>(); try (ResultSet rs = stmt.getGeneratedKeys()) { final List columnLabels = JdbcUtil.getColumnLabelList(rs); while (rs.next()) { ids.add(autoGeneratedKeyExtractor.apply(rs, columnLabels)); } if (N.notNullOrEmpty(ids) && Stream.of(ids).allMatch(Fn.isNull())) { ids = new ArrayList<>(); } return ids; } finally { stmt.clearBatch(); } } finally { closeAfterExecutionIfAllowed(); } } /** * * @return * @throws SQLException the SQL exception */ public int update() throws SQLException { assertNotClosed(); try { return stmt.executeUpdate(); } finally { closeAfterExecutionIfAllowed(); } } /** * * @return * @throws SQLException the SQL exception */ public int[] batchUpdate() throws SQLException { assertNotClosed(); try { try { int[] result = stmt.executeBatch(); return result; } finally { stmt.clearBatch(); } } finally { closeAfterExecutionIfAllowed(); } } /** * * @return * @throws SQLException the SQL exception */ public long largeUpate() throws SQLException { assertNotClosed(); try { return stmt.executeLargeUpdate(); } finally { closeAfterExecutionIfAllowed(); } } /** * Large batch update. * * @return * @throws SQLException the SQL exception */ public long[] largeBatchUpdate() throws SQLException { assertNotClosed(); try { try { return stmt.executeLargeBatch(); } finally { stmt.clearBatch(); } } finally { closeAfterExecutionIfAllowed(); } } /** * * @return true, if successful * @throws SQLException the SQL exception */ public boolean execute() throws SQLException { assertNotClosed(); try { return stmt.execute(); } finally { closeAfterExecutionIfAllowed(); } } /** * Execute then apply. * * @param * @param getter * @return * @throws SQLException the SQL exception */ public R executeThenApply(final Try.Function getter) throws SQLException { checkArgNotNull(getter, "getter"); assertNotClosed(); try { stmt.execute(); return getter.apply(stmt); } finally { closeAfterExecutionIfAllowed(); } } /** * Execute then apply. * * @param * @param getter * @return * @throws SQLException the SQL exception */ public R executeThenApply(final Try.BiFunction getter) throws SQLException { checkArgNotNull(getter, "getter"); assertNotClosed(); try { final boolean isFirstResultSet = stmt.execute(); return getter.apply(isFirstResultSet, stmt); } finally { closeAfterExecutionIfAllowed(); } } /** * Execute then accept. * * @param consumer * @throws SQLException the SQL exception */ public void executeThenAccept(final Try.Consumer consumer) throws SQLException { checkArgNotNull(consumer, "consumer"); assertNotClosed(); try { stmt.execute(); consumer.accept(stmt); } finally { closeAfterExecutionIfAllowed(); } } /** * Execute then accept. * * @param consumer * @throws SQLException the SQL exception */ public void executeThenAccept(final Try.BiConsumer consumer) throws SQLException { checkArgNotNull(consumer, "consumer"); assertNotClosed(); try { final boolean isFirstResultSet = stmt.execute(); consumer.accept(isFirstResultSet, stmt); } finally { closeAfterExecutionIfAllowed(); } } /** * * @param * @param func * @return */ @Beta public ContinuableFuture asyncApply(final Try.Function func) { checkArgNotNull(func, "func"); assertNotClosed(); final Q q = (Q) this; return asyncExecutor.execute(() -> func.apply(q)); } /** * * @param * @param func * @param executor * @return */ @Beta public ContinuableFuture asyncApply(final Try.Function func, final Executor executor) { checkArgNotNull(func, "func"); checkArgNotNull(executor, "executor"); assertNotClosed(); final Q q = (Q) this; return ContinuableFuture.call(() -> func.apply(q), executor); } /** * * @param action * @return */ @Beta public ContinuableFuture asyncAccept(final Try.Consumer action) { checkArgNotNull(action, "action"); assertNotClosed(); final Q q = (Q) this; return asyncExecutor.execute(() -> action.accept(q)); } /** * * @param action * @param executor * @return */ @Beta public ContinuableFuture asyncAccept(final Try.Consumer action, final Executor executor) { checkArgNotNull(action, "action"); checkArgNotNull(executor, "executor"); assertNotClosed(); final Q q = (Q) this; return ContinuableFuture.run(() -> action.accept(q), executor); } /** * Check arg not null. * * @param arg * @param argName */ protected void checkArgNotNull(Object arg, String argName) { if (arg == null) { try { close(); } catch (Exception e) { logger.error("Failed to close PreparedQuery", e); } throw new IllegalArgumentException("'" + argName + "' can't be null"); } } /** * * @param b * @param errorMsg */ protected void checkArg(boolean b, String errorMsg) { if (b == false) { try { close(); } catch (Exception e) { logger.error("Failed to close PreparedQuery", e); } throw new IllegalArgumentException(errorMsg); } } protected R checkNotResultSet(R result) { if (result instanceof ResultSet) { throw new UnsupportedOperationException("The result value of ResultExtractor/BiResultExtractor.apply can't be ResultSet"); } return result; } /** * Close. */ @Override public void close() { if (isClosed) { return; } isClosed = true; try { if (isBatch) { stmt.clearBatch(); } else { stmt.clearParameters(); } } catch (SQLException e) { logger.error("Failed to clear the parameters set in Statements", e); } finally { if (closeHandler == null) { JdbcUtil.closeQuietly(stmt); } else { try { JdbcUtil.closeQuietly(stmt); } finally { closeHandler.run(); } } } } /** * Close after execution if allowed. * * @throws SQLException the SQL exception */ void closeAfterExecutionIfAllowed() throws SQLException { if (isCloseAfterExecution) { close(); } } /** * Assert not closed. */ void assertNotClosed() { if (isClosed) { throw new IllegalStateException(); } } } /** * The backed {@code PreparedStatement/CallableStatement} will be closed by default * after any execution methods(which will trigger the backed {@code PreparedStatement/CallableStatement} to be executed, for example: get/query/queryForInt/Long/../findFirst/list/execute/...). * except the {@code 'closeAfterExecution'} flag is set to {@code false} by calling {@code #closeAfterExecution(false)}. * *
* Generally, don't cache or reuse the instance of this class, * except the {@code 'closeAfterExecution'} flag is set to {@code false} by calling {@code #closeAfterExecution(false)}. * *
* The {@code ResultSet} returned by query will always be closed after execution, even {@code 'closeAfterExecution'} flag is set to {@code false}. * *
* Remember: parameter/column index in {@code PreparedStatement/ResultSet} starts from 1, not 0. * * @author haiyangl * * @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 */ public static class PreparedQuery extends AbstractPreparedQuery { /** * Instantiates a new prepared query. * * @param stmt */ PreparedQuery(PreparedStatement stmt) { super(stmt); } } /** * The backed {@code PreparedStatement/CallableStatement} will be closed by default * after any execution methods(which will trigger the backed {@code PreparedStatement/CallableStatement} to be executed, for example: get/query/queryForInt/Long/../findFirst/list/execute/...). * except the {@code 'closeAfterExecution'} flag is set to {@code false} by calling {@code #closeAfterExecution(false)}. * *
* Generally, don't cache or reuse the instance of this class, * except the {@code 'closeAfterExecution'} flag is set to {@code false} by calling {@code #closeAfterExecution(false)}. * *
* The {@code ResultSet} returned by query will always be closed after execution, even {@code 'closeAfterExecution'} flag is set to {@code false}. * *
* Remember: parameter/column index in {@code PreparedStatement/ResultSet} starts from 1, not 0. * * @author haiyangl * * @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 */ public static class PreparedCallableQuery extends AbstractPreparedQuery { /** The stmt. */ final CallableStatement stmt; /** * Instantiates a new prepared callable query. * * @param stmt */ PreparedCallableQuery(CallableStatement stmt) { super(stmt); this.stmt = stmt; } /** * Sets the null. * * @param parameterName * @param sqlType * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setNull(String parameterName, int sqlType) throws SQLException { stmt.setNull(parameterName, sqlType); return this; } /** * Sets the null. * * @param parameterName * @param sqlType * @param typeName * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setNull(String parameterName, int sqlType, String typeName) throws SQLException { stmt.setNull(parameterName, sqlType, typeName); return this; } /** * Sets the boolean. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setBoolean(String parameterName, boolean x) throws SQLException { stmt.setBoolean(parameterName, x); return this; } /** * Sets the boolean. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setBoolean(String parameterName, Boolean x) throws SQLException { stmt.setBoolean(parameterName, N.defaultIfNull(x)); return this; } /** * Sets the byte. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setByte(String parameterName, byte x) throws SQLException { stmt.setByte(parameterName, x); return this; } /** * Sets the byte. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setByte(String parameterName, Byte x) throws SQLException { stmt.setByte(parameterName, N.defaultIfNull(x)); return this; } /** * Sets the short. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setShort(String parameterName, short x) throws SQLException { stmt.setShort(parameterName, x); return this; } /** * Sets the short. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setShort(String parameterName, Short x) throws SQLException { stmt.setShort(parameterName, N.defaultIfNull(x)); return this; } /** * Sets the int. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setInt(String parameterName, int x) throws SQLException { stmt.setInt(parameterName, x); return this; } /** * Sets the int. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setInt(String parameterName, Integer x) throws SQLException { stmt.setInt(parameterName, N.defaultIfNull(x)); return this; } /** * Sets the long. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setLong(String parameterName, long x) throws SQLException { stmt.setLong(parameterName, x); return this; } /** * Sets the long. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setLong(String parameterName, Long x) throws SQLException { stmt.setLong(parameterName, N.defaultIfNull(x)); return this; } /** * Sets the float. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setFloat(String parameterName, float x) throws SQLException { stmt.setFloat(parameterName, x); return this; } /** * Sets the float. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setFloat(String parameterName, Float x) throws SQLException { stmt.setFloat(parameterName, N.defaultIfNull(x)); return this; } /** * Sets the double. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setDouble(String parameterName, double x) throws SQLException { stmt.setDouble(parameterName, x); return this; } /** * Sets the double. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setDouble(String parameterName, Double x) throws SQLException { stmt.setDouble(parameterName, N.defaultIfNull(x)); return this; } /** * Sets the big decimal. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setBigDecimal(String parameterName, BigDecimal x) throws SQLException { stmt.setBigDecimal(parameterName, x); return this; } /** * Sets the string. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setString(String parameterName, String x) throws SQLException { stmt.setString(parameterName, x); return this; } /** * Sets the date. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setDate(String parameterName, java.sql.Date x) throws SQLException { stmt.setDate(parameterName, x); return this; } /** * Sets the date. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setDate(String parameterName, java.util.Date x) throws SQLException { stmt.setDate(parameterName, x == null ? null : x instanceof java.sql.Date ? (java.sql.Date) x : new java.sql.Date(x.getTime())); return this; } /** * Sets the time. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setTime(String parameterName, java.sql.Time x) throws SQLException { stmt.setTime(parameterName, x); return this; } /** * Sets the time. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setTime(String parameterName, java.util.Date x) throws SQLException { stmt.setTime(parameterName, x == null ? null : x instanceof java.sql.Time ? (java.sql.Time) x : new java.sql.Time(x.getTime())); return this; } /** * Sets the timestamp. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setTimestamp(String parameterName, java.sql.Timestamp x) throws SQLException { stmt.setTimestamp(parameterName, x); return this; } /** * Sets the timestamp. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setTimestamp(String parameterName, java.util.Date x) throws SQLException { stmt.setTimestamp(parameterName, x == null ? null : x instanceof java.sql.Timestamp ? (java.sql.Timestamp) x : new java.sql.Timestamp(x.getTime())); return this; } /** * Sets the bytes. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setBytes(String parameterName, byte[] x) throws SQLException { stmt.setBytes(parameterName, x); return this; } /** * Sets the ascii stream. * * @param parameterName * @param inputStream * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setAsciiStream(String parameterName, InputStream inputStream) throws SQLException { stmt.setAsciiStream(parameterName, inputStream); return this; } /** * Sets the ascii stream. * * @param parameterName * @param inputStream * @param length * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setAsciiStream(String parameterName, InputStream inputStream, long length) throws SQLException { stmt.setAsciiStream(parameterName, inputStream, length); return this; } /** * Sets the binary stream. * * @param parameterName * @param inputStream * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setBinaryStream(String parameterName, InputStream inputStream) throws SQLException { stmt.setBinaryStream(parameterName, inputStream); return this; } /** * Sets the binary stream. * * @param parameterName * @param inputStream * @param length * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setBinaryStream(String parameterName, InputStream inputStream, long length) throws SQLException { stmt.setBinaryStream(parameterName, inputStream, length); return this; } /** * Sets the character stream. * * @param parameterName * @param reader * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setCharacterStream(String parameterName, Reader reader) throws SQLException { stmt.setCharacterStream(parameterName, reader); return this; } /** * Sets the character stream. * * @param parameterName * @param reader * @param length * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setCharacterStream(String parameterName, Reader reader, long length) throws SQLException { stmt.setCharacterStream(parameterName, reader, length); return this; } /** * Sets the N character stream. * * @param parameterName * @param reader * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setNCharacterStream(String parameterName, Reader reader) throws SQLException { stmt.setNCharacterStream(parameterName, reader); return this; } /** * Sets the N character stream. * * @param parameterName * @param reader * @param length * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setNCharacterStream(String parameterName, Reader reader, long length) throws SQLException { stmt.setNCharacterStream(parameterName, reader, length); return this; } /** * Sets the blob. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setBlob(String parameterName, java.sql.Blob x) throws SQLException { stmt.setBlob(parameterName, x); return this; } /** * Sets the blob. * * @param parameterName * @param inputStream * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setBlob(String parameterName, InputStream inputStream) throws SQLException { stmt.setBlob(parameterName, inputStream); return this; } /** * Sets the blob. * * @param parameterName * @param inputStream * @param length * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setBlob(String parameterName, InputStream inputStream, long length) throws SQLException { stmt.setBlob(parameterName, inputStream, length); return this; } /** * Sets the clob. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setClob(String parameterName, java.sql.Clob x) throws SQLException { stmt.setClob(parameterName, x); return this; } /** * Sets the clob. * * @param parameterName * @param reader * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setClob(String parameterName, Reader reader) throws SQLException { stmt.setClob(parameterName, reader); return this; } /** * Sets the clob. * * @param parameterName * @param reader * @param length * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setClob(String parameterName, Reader reader, long length) throws SQLException { stmt.setClob(parameterName, reader, length); return this; } /** * Sets the N clob. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setNClob(String parameterName, java.sql.NClob x) throws SQLException { stmt.setNClob(parameterName, x); return this; } /** * Sets the N clob. * * @param parameterName * @param reader * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setNClob(String parameterName, Reader reader) throws SQLException { stmt.setNClob(parameterName, reader); return this; } /** * Sets the N clob. * * @param parameterName * @param reader * @param length * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setNClob(String parameterName, Reader reader, long length) throws SQLException { stmt.setNClob(parameterName, reader, length); return this; } /** * * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setURL(String parameterName, URL x) throws SQLException { stmt.setURL(parameterName, x); return this; } /** * * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setSQLXML(String parameterName, java.sql.SQLXML x) throws SQLException { stmt.setSQLXML(parameterName, x); return this; } /** * * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setRowId(String parameterName, java.sql.RowId x) throws SQLException { stmt.setRowId(parameterName, x); return this; } /** * Sets the object. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setObject(String parameterName, Object x) throws SQLException { if (x == null) { stmt.setObject(parameterName, x); } else { N.typeOf(x.getClass()).set(stmt, parameterName, x); } return this; } /** * Sets the object. * * @param parameterName * @param x * @param sqlType * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setObject(String parameterName, Object x, int sqlType) throws SQLException { stmt.setObject(parameterName, x, sqlType); return this; } /** * Sets the object. * * @param parameterName * @param x * @param sqlType * @param scaleOrLength * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setObject(String parameterName, Object x, int sqlType, int scaleOrLength) throws SQLException { stmt.setObject(parameterName, x, sqlType, scaleOrLength); return this; } /** * Sets the parameters. * * @param parameters * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery setParameters(Map parameters) throws SQLException { checkArgNotNull(parameters, "parameters"); for (Map.Entry entry : parameters.entrySet()) { setObject(entry.getKey(), entry.getValue()); } return this; } /** * Sets the parameters. * * @param parameterNames * @param entity * @return * @throws SQLException the SQL exception * @see {@link ClassUtil#getPropNameList(Class)} * @see {@link ClassUtil#getPropNameListExclusively(Class, Set)} * @see {@link ClassUtil#getPropNameListExclusively(Class, Collection)} * @see {@link JdbcUtil#getNamedParameters(String)} */ public PreparedCallableQuery setParameters(List parameterNames, Object entity) throws SQLException { checkArgNotNull(parameterNames, "parameterNames"); checkArgNotNull(entity, "entity"); final Class cls = entity.getClass(); final EntityInfo entityInfo = ParserUtil.getEntityInfo(cls); PropInfo propInfo = null; for (String parameterName : parameterNames) { propInfo = entityInfo.getPropInfo(parameterName); propInfo.dbType.set(stmt, parameterName, propInfo.getPropValue(entity)); } return this; } /** * Register out parameter. * * @param parameterIndex starts from 1, not 0. * @param sqlType * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery registerOutParameter(int parameterIndex, int sqlType) throws SQLException { stmt.registerOutParameter(parameterIndex, sqlType); return this; } /** * Register out parameter. * * @param parameterIndex starts from 1, not 0. * @param sqlType * @param scale * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery registerOutParameter(int parameterIndex, int sqlType, int scale) throws SQLException { stmt.registerOutParameter(parameterIndex, sqlType, scale); return this; } /** * Register out parameter. * * @param parameterIndex starts from 1, not 0. * @param sqlType * @param typeName * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery registerOutParameter(int parameterIndex, int sqlType, String typeName) throws SQLException { stmt.registerOutParameter(parameterIndex, sqlType, typeName); return this; } /** * Register out parameter. * * @param parameterName * @param sqlType * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery registerOutParameter(String parameterName, int sqlType) throws SQLException { stmt.registerOutParameter(parameterName, sqlType); return this; } /** * Register out parameter. * * @param parameterName * @param sqlType * @param scale * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery registerOutParameter(String parameterName, int sqlType, int scale) throws SQLException { stmt.registerOutParameter(parameterName, sqlType, scale); return this; } /** * Register out parameter. * * @param parameterName * @param sqlType * @param typeName * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery registerOutParameter(String parameterName, int sqlType, String typeName) throws SQLException { stmt.registerOutParameter(parameterName, sqlType, typeName); return this; } /** * Register out parameter. * * @param parameterIndex starts from 1, not 0. * @param sqlType * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery registerOutParameter(int parameterIndex, SQLType sqlType) throws SQLException { stmt.registerOutParameter(parameterIndex, sqlType); return this; } /** * Register out parameter. * * @param parameterIndex starts from 1, not 0. * @param sqlType * @param scale * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery registerOutParameter(int parameterIndex, SQLType sqlType, int scale) throws SQLException { stmt.registerOutParameter(parameterIndex, sqlType, scale); return this; } /** * Register out parameter. * * @param parameterIndex starts from 1, not 0. * @param sqlType * @param typeName * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery registerOutParameter(int parameterIndex, SQLType sqlType, String typeName) throws SQLException { stmt.registerOutParameter(parameterIndex, sqlType, typeName); return this; } /** * Register out parameter. * * @param parameterName * @param sqlType * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery registerOutParameter(String parameterName, SQLType sqlType) throws SQLException { stmt.registerOutParameter(parameterName, sqlType); return this; } /** * Register out parameter. * * @param parameterName * @param sqlType * @param scale * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery registerOutParameter(String parameterName, SQLType sqlType, int scale) throws SQLException { stmt.registerOutParameter(parameterName, sqlType, scale); return this; } /** * Register out parameter. * * @param parameterName * @param sqlType * @param typeName * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery registerOutParameter(String parameterName, SQLType sqlType, String typeName) throws SQLException { stmt.registerOutParameter(parameterName, sqlType, typeName); return this; } /** * Register out parameters. * * @param register * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery registerOutParameters(final ParametersSetter register) throws SQLException { checkArgNotNull(register, "register"); boolean noException = false; try { register.accept(stmt); noException = true; } finally { if (noException == false) { close(); } } return this; } /** * Register out parameters. * * @param * @param parameter * @param register * @return * @throws SQLException the SQL exception */ public PreparedCallableQuery registerOutParameters(final T parameter, final BiParametersSetter register) throws SQLException { checkArgNotNull(register, "register"); boolean noException = false; try { register.accept(parameter, stmt); noException = true; } finally { if (noException == false) { close(); } } return this; } /** * * @param * @param resultExtrator1 * @return * @throws SQLException the SQL exception */ public Optional call(final ResultExtractor resultExtrator1) throws SQLException { checkArgNotNull(resultExtrator1, "resultExtrator1"); assertNotClosed(); try { if (stmt.execute()) { if (stmt.getUpdateCount() == -1) { try (ResultSet rs = stmt.getResultSet()) { return Optional.of(checkNotResultSet(resultExtrator1.apply(rs))); } } } } finally { closeAfterExecutionIfAllowed(); } return Optional.empty(); } /** * * @param * @param * @param resultExtrator1 * @param resultExtrator2 * @return * @throws SQLException the SQL exception */ public Tuple2, Optional> call(final ResultExtractor resultExtrator1, final ResultExtractor resultExtrator2) throws SQLException { checkArgNotNull(resultExtrator1, "resultExtrator1"); checkArgNotNull(resultExtrator2, "resultExtrator2"); assertNotClosed(); Optional result1 = Optional.empty(); Optional result2 = Optional.empty(); try { if (stmt.execute()) { if (stmt.getUpdateCount() == -1) { try (ResultSet rs = stmt.getResultSet()) { result1 = Optional.of(checkNotResultSet(resultExtrator1.apply(rs))); } } if (stmt.getMoreResults() && stmt.getUpdateCount() == -1) { try (ResultSet rs = stmt.getResultSet()) { result2 = Optional.of(checkNotResultSet(resultExtrator2.apply(rs))); } } } } finally { closeAfterExecutionIfAllowed(); } return Tuple.of(result1, result2); } /** * * @param * @param * @param * @param resultExtrator1 * @param resultExtrator2 * @param resultExtrator3 * @return * @throws SQLException the SQL exception */ public Tuple3, Optional, Optional> call(final ResultExtractor resultExtrator1, final ResultExtractor resultExtrator2, final ResultExtractor resultExtrator3) throws SQLException { checkArgNotNull(resultExtrator1, "resultExtrator1"); checkArgNotNull(resultExtrator2, "resultExtrator2"); checkArgNotNull(resultExtrator3, "resultExtrator3"); assertNotClosed(); Optional result1 = Optional.empty(); Optional result2 = Optional.empty(); Optional result3 = Optional.empty(); try { if (stmt.execute()) { if (stmt.getUpdateCount() == -1) { try (ResultSet rs = stmt.getResultSet()) { result1 = Optional.of(checkNotResultSet(resultExtrator1.apply(rs))); } } if (stmt.getMoreResults() && stmt.getUpdateCount() == -1) { try (ResultSet rs = stmt.getResultSet()) { result2 = Optional.of(checkNotResultSet(resultExtrator2.apply(rs))); } } if (stmt.getMoreResults() && stmt.getUpdateCount() == -1) { try (ResultSet rs = stmt.getResultSet()) { result3 = Optional.of(checkNotResultSet(resultExtrator3.apply(rs))); } } } } finally { closeAfterExecutionIfAllowed(); } return Tuple.of(result1, result2, result3); } /** * * @param * @param * @param * @param * @param resultExtrator1 * @param resultExtrator2 * @param resultExtrator3 * @param resultExtrator4 * @return * @throws SQLException the SQL exception */ public Tuple4, Optional, Optional, Optional> call(final ResultExtractor resultExtrator1, final ResultExtractor resultExtrator2, final ResultExtractor resultExtrator3, final ResultExtractor resultExtrator4) throws SQLException { checkArgNotNull(resultExtrator1, "resultExtrator1"); checkArgNotNull(resultExtrator2, "resultExtrator2"); checkArgNotNull(resultExtrator3, "resultExtrator3"); checkArgNotNull(resultExtrator4, "resultExtrator4"); assertNotClosed(); Optional result1 = Optional.empty(); Optional result2 = Optional.empty(); Optional result3 = Optional.empty(); Optional result4 = Optional.empty(); try { if (stmt.execute()) { if (stmt.getUpdateCount() == -1) { try (ResultSet rs = stmt.getResultSet()) { result1 = Optional.of(checkNotResultSet(resultExtrator1.apply(rs))); } } if (stmt.getMoreResults() && stmt.getUpdateCount() == -1) { try (ResultSet rs = stmt.getResultSet()) { result2 = Optional.of(checkNotResultSet(resultExtrator2.apply(rs))); } } if (stmt.getMoreResults() && stmt.getUpdateCount() == -1) { try (ResultSet rs = stmt.getResultSet()) { result3 = Optional.of(checkNotResultSet(resultExtrator3.apply(rs))); } } if (stmt.getMoreResults() && stmt.getUpdateCount() == -1) { try (ResultSet rs = stmt.getResultSet()) { result4 = Optional.of(checkNotResultSet(resultExtrator4.apply(rs))); } } } } finally { closeAfterExecutionIfAllowed(); } return Tuple.of(result1, result2, result3, result4); } /** * * @param * @param * @param * @param * @param * @param resultExtrator1 * @param resultExtrator2 * @param resultExtrator3 * @param resultExtrator4 * @param resultExtrator5 * @return * @throws SQLException the SQL exception */ public Tuple5, Optional, Optional, Optional, Optional> call(final ResultExtractor resultExtrator1, final ResultExtractor resultExtrator2, final ResultExtractor resultExtrator3, final ResultExtractor resultExtrator4, final ResultExtractor resultExtrator5) throws SQLException { checkArgNotNull(resultExtrator1, "resultExtrator1"); checkArgNotNull(resultExtrator2, "resultExtrator2"); checkArgNotNull(resultExtrator3, "resultExtrator3"); checkArgNotNull(resultExtrator4, "resultExtrator4"); checkArgNotNull(resultExtrator5, "resultExtrator5"); assertNotClosed(); Optional result1 = Optional.empty(); Optional result2 = Optional.empty(); Optional result3 = Optional.empty(); Optional result4 = Optional.empty(); Optional result5 = Optional.empty(); try { if (stmt.execute()) { if (stmt.getUpdateCount() == -1) { try (ResultSet rs = stmt.getResultSet()) { result1 = Optional.of(checkNotResultSet(resultExtrator1.apply(rs))); } } if (stmt.getMoreResults() && stmt.getUpdateCount() == -1) { try (ResultSet rs = stmt.getResultSet()) { result2 = Optional.of(checkNotResultSet(resultExtrator2.apply(rs))); } } if (stmt.getMoreResults() && stmt.getUpdateCount() == -1) { try (ResultSet rs = stmt.getResultSet()) { result3 = Optional.of(checkNotResultSet(resultExtrator3.apply(rs))); } } if (stmt.getMoreResults() && stmt.getUpdateCount() == -1) { try (ResultSet rs = stmt.getResultSet()) { result4 = Optional.of(checkNotResultSet(resultExtrator4.apply(rs))); } } if (stmt.getMoreResults() && stmt.getUpdateCount() == -1) { try (ResultSet rs = stmt.getResultSet()) { result5 = Optional.of(checkNotResultSet(resultExtrator5.apply(rs))); } } } } finally { closeAfterExecutionIfAllowed(); } return Tuple.of(result1, result2, result3, result4, result5); } } /** * The backed {@code PreparedStatement/CallableStatement} will be closed by default * after any execution methods(which will trigger the backed {@code PreparedStatement/CallableStatement} to be executed, for example: get/query/queryForInt/Long/../findFirst/list/execute/...). * except the {@code 'closeAfterExecution'} flag is set to {@code false} by calling {@code #closeAfterExecution(false)}. * *
* Generally, don't cache or reuse the instance of this class, * except the {@code 'closeAfterExecution'} flag is set to {@code false} by calling {@code #closeAfterExecution(false)}. * *
* The {@code ResultSet} returned by query will always be closed after execution, even {@code 'closeAfterExecution'} flag is set to {@code false}. * *
* Remember: parameter/column index in {@code PreparedStatement/ResultSet} starts from 1, not 0. * * @author haiyangl * * @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 */ public static class NamedQuery extends AbstractPreparedQuery { /** The named SQL. */ private final NamedSQL namedSQL; /** The parameter names. */ private final List parameterNames; /** The parameter count. */ private final int parameterCount; /** The param name index map. */ private Map paramNameIndexMap; /** * Instantiates a new named query. * * @param stmt * @param namedSQL */ NamedQuery(final PreparedStatement stmt, final NamedSQL namedSQL) { super(stmt); this.namedSQL = namedSQL; this.parameterNames = namedSQL.getNamedParameters(); this.parameterCount = namedSQL.getParameterCount(); } /** * Inits the param name index map. */ private void initParamNameIndexMap() { paramNameIndexMap = new HashMap<>(parameterCount); int index = 1; for (String paramName : parameterNames) { IntList indexes = paramNameIndexMap.get(paramName); if (indexes == null) { indexes = new IntList(1); paramNameIndexMap.put(paramName, indexes); } indexes.add(index++); } } /** * Sets the null. * * @param parameterName * @param sqlType * @return * @throws SQLException the SQL exception */ public NamedQuery setNull(String parameterName, int sqlType) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setNull(i + 1, sqlType); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setNull(indexes.get(0), sqlType); } else if (indexes.size() == 2) { setNull(indexes.get(0), sqlType); setNull(indexes.get(1), sqlType); } else if (indexes.size() == 3) { setNull(indexes.get(0), sqlType); setNull(indexes.get(1), sqlType); setNull(indexes.get(2), sqlType); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setNull(indexes.get(i), sqlType); } } } } return this; } /** * Sets the null. * * @param parameterName * @param sqlType * @param typeName * @return * @throws SQLException the SQL exception */ public NamedQuery setNull(String parameterName, int sqlType, String typeName) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setNull(i + 1, sqlType, typeName); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setNull(indexes.get(0), sqlType, typeName); } else if (indexes.size() == 2) { setNull(indexes.get(0), sqlType, typeName); setNull(indexes.get(1), sqlType, typeName); } else if (indexes.size() == 3) { setNull(indexes.get(0), sqlType, typeName); setNull(indexes.get(1), sqlType, typeName); setNull(indexes.get(2), sqlType, typeName); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setNull(indexes.get(i), sqlType, typeName); } } } } return this; } /** * Sets the boolean. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public NamedQuery setBoolean(String parameterName, boolean x) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setBoolean(i + 1, x); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setBoolean(indexes.get(0), x); } else if (indexes.size() == 2) { setBoolean(indexes.get(0), x); setBoolean(indexes.get(1), x); } else if (indexes.size() == 3) { setBoolean(indexes.get(0), x); setBoolean(indexes.get(1), x); setBoolean(indexes.get(2), x); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setBoolean(indexes.get(i), x); } } } } return this; } /** * Sets the boolean. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public NamedQuery setBoolean(String parameterName, Boolean x) throws SQLException { setBoolean(parameterName, N.defaultIfNull(x)); return this; } /** * Sets the byte. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public NamedQuery setByte(String parameterName, byte x) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setByte(i + 1, x); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setByte(indexes.get(0), x); } else if (indexes.size() == 2) { setByte(indexes.get(0), x); setByte(indexes.get(1), x); } else if (indexes.size() == 3) { setByte(indexes.get(0), x); setByte(indexes.get(1), x); setByte(indexes.get(2), x); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setByte(indexes.get(i), x); } } } } return this; } /** * Sets the byte. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public NamedQuery setByte(String parameterName, Byte x) throws SQLException { setByte(parameterName, N.defaultIfNull(x)); return this; } /** * Sets the short. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public NamedQuery setShort(String parameterName, short x) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setShort(i + 1, x); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setShort(indexes.get(0), x); } else if (indexes.size() == 2) { setShort(indexes.get(0), x); setShort(indexes.get(1), x); } else if (indexes.size() == 3) { setShort(indexes.get(0), x); setShort(indexes.get(1), x); setShort(indexes.get(2), x); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setShort(indexes.get(i), x); } } } } return this; } /** * Sets the short. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public NamedQuery setShort(String parameterName, Short x) throws SQLException { setShort(parameterName, N.defaultIfNull(x)); return this; } /** * Sets the int. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public NamedQuery setInt(String parameterName, int x) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setInt(i + 1, x); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setInt(indexes.get(0), x); } else if (indexes.size() == 2) { setInt(indexes.get(0), x); setInt(indexes.get(1), x); } else if (indexes.size() == 3) { setInt(indexes.get(0), x); setInt(indexes.get(1), x); setInt(indexes.get(2), x); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setInt(indexes.get(i), x); } } } } return this; } /** * Sets the int. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public NamedQuery setInt(String parameterName, Integer x) throws SQLException { setInt(parameterName, N.defaultIfNull(x)); return this; } /** * Sets the long. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public NamedQuery setLong(String parameterName, long x) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setLong(i + 1, x); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setLong(indexes.get(0), x); } else if (indexes.size() == 2) { setLong(indexes.get(0), x); setLong(indexes.get(1), x); } else if (indexes.size() == 3) { setLong(indexes.get(0), x); setLong(indexes.get(1), x); setLong(indexes.get(2), x); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setLong(indexes.get(i), x); } } } } return this; } /** * Sets the long. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public NamedQuery setLong(String parameterName, Long x) throws SQLException { setLong(parameterName, N.defaultIfNull(x)); return this; } /** * Sets the float. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public NamedQuery setFloat(String parameterName, float x) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setFloat(i + 1, x); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setFloat(indexes.get(0), x); } else if (indexes.size() == 2) { setFloat(indexes.get(0), x); setFloat(indexes.get(1), x); } else if (indexes.size() == 3) { setFloat(indexes.get(0), x); setFloat(indexes.get(1), x); setFloat(indexes.get(2), x); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setFloat(indexes.get(i), x); } } } } return this; } /** * Sets the float. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public NamedQuery setFloat(String parameterName, Float x) throws SQLException { setFloat(parameterName, N.defaultIfNull(x)); return this; } /** * Sets the double. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public NamedQuery setDouble(String parameterName, double x) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setDouble(i + 1, x); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setDouble(indexes.get(0), x); } else if (indexes.size() == 2) { setDouble(indexes.get(0), x); setDouble(indexes.get(1), x); } else if (indexes.size() == 3) { setDouble(indexes.get(0), x); setDouble(indexes.get(1), x); setDouble(indexes.get(2), x); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setDouble(indexes.get(i), x); } } } } return this; } /** * Sets the double. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public NamedQuery setDouble(String parameterName, Double x) throws SQLException { setDouble(parameterName, N.defaultIfNull(x)); return this; } /** * Sets the big decimal. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public NamedQuery setBigDecimal(String parameterName, BigDecimal x) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setBigDecimal(i + 1, x); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setBigDecimal(indexes.get(0), x); } else if (indexes.size() == 2) { setBigDecimal(indexes.get(0), x); setBigDecimal(indexes.get(1), x); } else if (indexes.size() == 3) { setBigDecimal(indexes.get(0), x); setBigDecimal(indexes.get(1), x); setBigDecimal(indexes.get(2), x); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setBigDecimal(indexes.get(i), x); } } } } return this; } /** * Sets the string. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public NamedQuery setString(String parameterName, String x) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setString(i + 1, x); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setString(indexes.get(0), x); } else if (indexes.size() == 2) { setString(indexes.get(0), x); setString(indexes.get(1), x); } else if (indexes.size() == 3) { setString(indexes.get(0), x); setString(indexes.get(1), x); setString(indexes.get(2), x); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setString(indexes.get(i), x); } } } } return this; } /** * Sets the date. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public NamedQuery setDate(String parameterName, java.sql.Date x) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setDate(i + 1, x); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setDate(indexes.get(0), x); } else if (indexes.size() == 2) { setDate(indexes.get(0), x); setDate(indexes.get(1), x); } else if (indexes.size() == 3) { setDate(indexes.get(0), x); setDate(indexes.get(1), x); setDate(indexes.get(2), x); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setDate(indexes.get(i), x); } } } } return this; } /** * Sets the date. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public NamedQuery setDate(String parameterName, java.util.Date x) throws SQLException { setDate(parameterName, x == null ? null : x instanceof java.sql.Date ? (java.sql.Date) x : new java.sql.Date(x.getTime())); return this; } /** * Sets the time. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public NamedQuery setTime(String parameterName, java.sql.Time x) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setTime(i + 1, x); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setTime(indexes.get(0), x); } else if (indexes.size() == 2) { setTime(indexes.get(0), x); setTime(indexes.get(1), x); } else if (indexes.size() == 3) { setTime(indexes.get(0), x); setTime(indexes.get(1), x); setTime(indexes.get(2), x); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setTime(indexes.get(i), x); } } } } return this; } /** * Sets the time. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public NamedQuery setTime(String parameterName, java.util.Date x) throws SQLException { setTime(parameterName, x == null ? null : x instanceof java.sql.Time ? (java.sql.Time) x : new java.sql.Time(x.getTime())); return this; } /** * Sets the timestamp. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public NamedQuery setTimestamp(String parameterName, java.sql.Timestamp x) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setTimestamp(i + 1, x); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setTimestamp(indexes.get(0), x); } else if (indexes.size() == 2) { setTimestamp(indexes.get(0), x); setTimestamp(indexes.get(1), x); } else if (indexes.size() == 3) { setTimestamp(indexes.get(0), x); setTimestamp(indexes.get(1), x); setTimestamp(indexes.get(2), x); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setTimestamp(indexes.get(i), x); } } } } return this; } /** * Sets the timestamp. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public NamedQuery setTimestamp(String parameterName, java.util.Date x) throws SQLException { setTimestamp(parameterName, x == null ? null : x instanceof java.sql.Timestamp ? (java.sql.Timestamp) x : new java.sql.Timestamp(x.getTime())); return this; } /** * Sets the bytes. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public NamedQuery setBytes(String parameterName, byte[] x) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setBytes(i + 1, x); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setBytes(indexes.get(0), x); } else if (indexes.size() == 2) { setBytes(indexes.get(0), x); setBytes(indexes.get(1), x); } else if (indexes.size() == 3) { setBytes(indexes.get(0), x); setBytes(indexes.get(1), x); setBytes(indexes.get(2), x); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setBytes(indexes.get(i), x); } } } } return this; } /** * Sets the ascii stream. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public NamedQuery setAsciiStream(String parameterName, InputStream x) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setAsciiStream(i + 1, x); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setAsciiStream(indexes.get(0), x); } else if (indexes.size() == 2) { setAsciiStream(indexes.get(0), x); setAsciiStream(indexes.get(1), x); } else if (indexes.size() == 3) { setAsciiStream(indexes.get(0), x); setAsciiStream(indexes.get(1), x); setAsciiStream(indexes.get(2), x); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setAsciiStream(indexes.get(i), x); } } } } return this; } /** * Sets the ascii stream. * * @param parameterName * @param x * @param length * @return * @throws SQLException the SQL exception */ public NamedQuery setAsciiStream(String parameterName, InputStream x, long length) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setAsciiStream(i + 1, x, length); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setAsciiStream(indexes.get(0), x, length); } else if (indexes.size() == 2) { setAsciiStream(indexes.get(0), x, length); setAsciiStream(indexes.get(1), x, length); } else if (indexes.size() == 3) { setAsciiStream(indexes.get(0), x, length); setAsciiStream(indexes.get(1), x, length); setAsciiStream(indexes.get(2), x, length); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setAsciiStream(indexes.get(i), x, length); } } } } return this; } /** * Sets the binary stream. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public NamedQuery setBinaryStream(String parameterName, InputStream x) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setBinaryStream(i + 1, x); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setBinaryStream(indexes.get(0), x); } else if (indexes.size() == 2) { setBinaryStream(indexes.get(0), x); setBinaryStream(indexes.get(1), x); } else if (indexes.size() == 3) { setBinaryStream(indexes.get(0), x); setBinaryStream(indexes.get(1), x); setBinaryStream(indexes.get(2), x); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setBinaryStream(indexes.get(i), x); } } } } return this; } /** * Sets the binary stream. * * @param parameterName * @param x * @param length * @return * @throws SQLException the SQL exception */ public NamedQuery setBinaryStream(String parameterName, InputStream x, long length) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setBinaryStream(i + 1, x, length); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setBinaryStream(indexes.get(0), x, length); } else if (indexes.size() == 2) { setBinaryStream(indexes.get(0), x, length); setBinaryStream(indexes.get(1), x, length); } else if (indexes.size() == 3) { setBinaryStream(indexes.get(0), x, length); setBinaryStream(indexes.get(1), x, length); setBinaryStream(indexes.get(2), x, length); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setBinaryStream(indexes.get(i), x, length); } } } } return this; } /** * Sets the character stream. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public NamedQuery setCharacterStream(String parameterName, Reader x) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setCharacterStream(i + 1, x); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setCharacterStream(indexes.get(0), x); } else if (indexes.size() == 2) { setCharacterStream(indexes.get(0), x); setCharacterStream(indexes.get(1), x); } else if (indexes.size() == 3) { setCharacterStream(indexes.get(0), x); setCharacterStream(indexes.get(1), x); setCharacterStream(indexes.get(2), x); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setCharacterStream(indexes.get(i), x); } } } } return this; } /** * Sets the character stream. * * @param parameterName * @param x * @param length * @return * @throws SQLException the SQL exception */ public NamedQuery setCharacterStream(String parameterName, Reader x, long length) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setCharacterStream(i + 1, x, length); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setCharacterStream(indexes.get(0), x, length); } else if (indexes.size() == 2) { setCharacterStream(indexes.get(0), x, length); setCharacterStream(indexes.get(1), x, length); } else if (indexes.size() == 3) { setCharacterStream(indexes.get(0), x, length); setCharacterStream(indexes.get(1), x, length); setCharacterStream(indexes.get(2), x, length); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setCharacterStream(indexes.get(i), x, length); } } } } return this; } /** * Sets the N character stream. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public NamedQuery setNCharacterStream(String parameterName, Reader x) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setNCharacterStream(i + 1, x); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setNCharacterStream(indexes.get(0), x); } else if (indexes.size() == 2) { setNCharacterStream(indexes.get(0), x); setNCharacterStream(indexes.get(1), x); } else if (indexes.size() == 3) { setNCharacterStream(indexes.get(0), x); setNCharacterStream(indexes.get(1), x); setNCharacterStream(indexes.get(2), x); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setNCharacterStream(indexes.get(i), x); } } } } return this; } /** * Sets the N character stream. * * @param parameterName * @param x * @param length * @return * @throws SQLException the SQL exception */ public NamedQuery setNCharacterStream(String parameterName, Reader x, long length) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setNCharacterStream(i + 1, x, length); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setNCharacterStream(indexes.get(0), x, length); } else if (indexes.size() == 2) { setNCharacterStream(indexes.get(0), x, length); setNCharacterStream(indexes.get(1), x, length); } else if (indexes.size() == 3) { setNCharacterStream(indexes.get(0), x, length); setNCharacterStream(indexes.get(1), x, length); setNCharacterStream(indexes.get(2), x, length); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setNCharacterStream(indexes.get(i), x, length); } } } } return this; } /** * Sets the blob. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public NamedQuery setBlob(String parameterName, java.sql.Blob x) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setBlob(i + 1, x); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setBlob(indexes.get(0), x); } else if (indexes.size() == 2) { setBlob(indexes.get(0), x); setBlob(indexes.get(1), x); } else if (indexes.size() == 3) { setBlob(indexes.get(0), x); setBlob(indexes.get(1), x); setBlob(indexes.get(2), x); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setBlob(indexes.get(i), x); } } } } return this; } /** * Sets the blob. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public NamedQuery setBlob(String parameterName, InputStream x) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setBlob(i + 1, x); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setBlob(indexes.get(0), x); } else if (indexes.size() == 2) { setBlob(indexes.get(0), x); setBlob(indexes.get(1), x); } else if (indexes.size() == 3) { setBlob(indexes.get(0), x); setBlob(indexes.get(1), x); setBlob(indexes.get(2), x); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setBlob(indexes.get(i), x); } } } } return this; } /** * Sets the blob. * * @param parameterName * @param x * @param length * @return * @throws SQLException the SQL exception */ public NamedQuery setBlob(String parameterName, InputStream x, long length) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setBlob(i + 1, x, length); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setBlob(indexes.get(0), x, length); } else if (indexes.size() == 2) { setBlob(indexes.get(0), x, length); setBlob(indexes.get(1), x, length); } else if (indexes.size() == 3) { setBlob(indexes.get(0), x, length); setBlob(indexes.get(1), x, length); setBlob(indexes.get(2), x, length); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setBlob(indexes.get(i), x, length); } } } } return this; } /** * Sets the clob. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public NamedQuery setClob(String parameterName, java.sql.Clob x) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setClob(i + 1, x); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setClob(indexes.get(0), x); } else if (indexes.size() == 2) { setClob(indexes.get(0), x); setClob(indexes.get(1), x); } else if (indexes.size() == 3) { setClob(indexes.get(0), x); setClob(indexes.get(1), x); setClob(indexes.get(2), x); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setClob(indexes.get(i), x); } } } } return this; } /** * Sets the clob. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public NamedQuery setClob(String parameterName, Reader x) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setClob(i + 1, x); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setClob(indexes.get(0), x); } else if (indexes.size() == 2) { setClob(indexes.get(0), x); setClob(indexes.get(1), x); } else if (indexes.size() == 3) { setClob(indexes.get(0), x); setClob(indexes.get(1), x); setClob(indexes.get(2), x); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setClob(indexes.get(i), x); } } } } return this; } /** * Sets the clob. * * @param parameterName * @param x * @param length * @return * @throws SQLException the SQL exception */ public NamedQuery setClob(String parameterName, Reader x, long length) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setClob(i + 1, x, length); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setClob(indexes.get(0), x, length); } else if (indexes.size() == 2) { setClob(indexes.get(0), x, length); setClob(indexes.get(1), x, length); } else if (indexes.size() == 3) { setClob(indexes.get(0), x, length); setClob(indexes.get(1), x, length); setClob(indexes.get(2), x, length); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setClob(indexes.get(i), x, length); } } } } return this; } /** * Sets the N clob. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public NamedQuery setNClob(String parameterName, java.sql.NClob x) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setNClob(i + 1, x); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setNClob(indexes.get(0), x); } else if (indexes.size() == 2) { setNClob(indexes.get(0), x); setNClob(indexes.get(1), x); } else if (indexes.size() == 3) { setNClob(indexes.get(0), x); setNClob(indexes.get(1), x); setNClob(indexes.get(2), x); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setNClob(indexes.get(i), x); } } } } return this; } /** * Sets the N clob. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public NamedQuery setNClob(String parameterName, Reader x) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setNClob(i + 1, x); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setNClob(indexes.get(0), x); } else if (indexes.size() == 2) { setNClob(indexes.get(0), x); setNClob(indexes.get(1), x); } else if (indexes.size() == 3) { setNClob(indexes.get(0), x); setNClob(indexes.get(1), x); setNClob(indexes.get(2), x); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setNClob(indexes.get(i), x); } } } } return this; } /** * Sets the N clob. * * @param parameterName * @param x * @param length * @return * @throws SQLException the SQL exception */ public NamedQuery setNClob(String parameterName, Reader x, long length) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setNClob(i + 1, x, length); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setNClob(indexes.get(0), x, length); } else if (indexes.size() == 2) { setNClob(indexes.get(0), x, length); setNClob(indexes.get(1), x, length); } else if (indexes.size() == 3) { setNClob(indexes.get(0), x, length); setNClob(indexes.get(1), x, length); setNClob(indexes.get(2), x, length); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setNClob(indexes.get(i), x, length); } } } } return this; } /** * * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public NamedQuery setURL(String parameterName, URL x) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setURL(i + 1, x); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setURL(indexes.get(0), x); } else if (indexes.size() == 2) { setURL(indexes.get(0), x); setURL(indexes.get(1), x); } else if (indexes.size() == 3) { setURL(indexes.get(0), x); setURL(indexes.get(1), x); setURL(indexes.get(2), x); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setURL(indexes.get(i), x); } } } } return this; } /** * * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public NamedQuery setSQLXML(String parameterName, java.sql.SQLXML x) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setSQLXML(i + 1, x); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setSQLXML(indexes.get(0), x); } else if (indexes.size() == 2) { setSQLXML(indexes.get(0), x); setSQLXML(indexes.get(1), x); } else if (indexes.size() == 3) { setSQLXML(indexes.get(0), x); setSQLXML(indexes.get(1), x); setSQLXML(indexes.get(2), x); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setSQLXML(indexes.get(i), x); } } } } return this; } /** * * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public NamedQuery setRowId(String parameterName, java.sql.RowId x) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setRowId(i + 1, x); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setRowId(indexes.get(0), x); } else if (indexes.size() == 2) { setRowId(indexes.get(0), x); setRowId(indexes.get(1), x); } else if (indexes.size() == 3) { setRowId(indexes.get(0), x); setRowId(indexes.get(1), x); setRowId(indexes.get(2), x); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setRowId(indexes.get(i), x); } } } } return this; } /** * * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public NamedQuery setRef(String parameterName, java.sql.Ref x) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setRef(i + 1, x); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setRef(indexes.get(0), x); } else if (indexes.size() == 2) { setRef(indexes.get(0), x); setRef(indexes.get(1), x); } else if (indexes.size() == 3) { setRef(indexes.get(0), x); setRef(indexes.get(1), x); setRef(indexes.get(2), x); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setRef(indexes.get(i), x); } } } } return this; } /** * * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public NamedQuery setArray(String parameterName, java.sql.Array x) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setArray(i + 1, x); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setArray(indexes.get(0), x); } else if (indexes.size() == 2) { setArray(indexes.get(0), x); setArray(indexes.get(1), x); } else if (indexes.size() == 3) { setArray(indexes.get(0), x); setArray(indexes.get(1), x); setArray(indexes.get(2), x); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setArray(indexes.get(i), x); } } } } return this; } /** * Sets the object. * * @param parameterName * @param x * @return * @throws SQLException the SQL exception */ public NamedQuery setObject(String parameterName, Object x) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setObject(i + 1, x); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setObject(indexes.get(0), x); } else if (indexes.size() == 2) { setObject(indexes.get(0), x); setObject(indexes.get(1), x); } else if (indexes.size() == 3) { setObject(indexes.get(0), x); setObject(indexes.get(1), x); setObject(indexes.get(2), x); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setObject(indexes.get(i), x); } } } } return this; } /** * Sets the object. * * @param parameterName * @param x * @param sqlType * @return * @throws SQLException the SQL exception */ public NamedQuery setObject(String parameterName, Object x, int sqlType) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setObject(i + 1, x, sqlType); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setObject(indexes.get(0), x, sqlType); } else if (indexes.size() == 2) { setObject(indexes.get(0), x, sqlType); setObject(indexes.get(1), x, sqlType); } else if (indexes.size() == 3) { setObject(indexes.get(0), x, sqlType); setObject(indexes.get(1), x, sqlType); setObject(indexes.get(2), x, sqlType); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setObject(indexes.get(i), x, sqlType); } } } } return this; } /** * Sets the object. * * @param parameterName * @param x * @param sqlType * @param scaleOrLength * @return * @throws SQLException the SQL exception */ public NamedQuery setObject(String parameterName, Object x, int sqlType, int scaleOrLength) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setObject(i + 1, x, sqlType, scaleOrLength); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setObject(indexes.get(0), x, sqlType, scaleOrLength); } else if (indexes.size() == 2) { setObject(indexes.get(0), x, sqlType, scaleOrLength); setObject(indexes.get(1), x, sqlType, scaleOrLength); } else if (indexes.size() == 3) { setObject(indexes.get(0), x, sqlType, scaleOrLength); setObject(indexes.get(1), x, sqlType, scaleOrLength); setObject(indexes.get(2), x, sqlType, scaleOrLength); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setObject(indexes.get(i), x, sqlType, scaleOrLength); } } } } return this; } /** * Sets the object. * * @param parameterName * @param x * @param sqlType * @return * @throws SQLException the SQL exception */ public NamedQuery setObject(String parameterName, Object x, SQLType sqlType) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setObject(i + 1, x, sqlType); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setObject(indexes.get(0), x, sqlType); } else if (indexes.size() == 2) { setObject(indexes.get(0), x, sqlType); setObject(indexes.get(1), x, sqlType); } else if (indexes.size() == 3) { setObject(indexes.get(0), x, sqlType); setObject(indexes.get(1), x, sqlType); setObject(indexes.get(2), x, sqlType); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setObject(indexes.get(i), x, sqlType); } } } } return this; } /** * Sets the object. * * @param parameterName * @param x * @param sqlType * @param scaleOrLength * @return * @throws SQLException the SQL exception */ public NamedQuery setObject(String parameterName, Object x, SQLType sqlType, int scaleOrLength) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { setObject(i + 1, x, sqlType, scaleOrLength); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { setObject(indexes.get(0), x, sqlType, scaleOrLength); } else if (indexes.size() == 2) { setObject(indexes.get(0), x, sqlType, scaleOrLength); setObject(indexes.get(1), x, sqlType, scaleOrLength); } else if (indexes.size() == 3) { setObject(indexes.get(0), x, sqlType, scaleOrLength); setObject(indexes.get(1), x, sqlType, scaleOrLength); setObject(indexes.get(2), x, sqlType, scaleOrLength); } else { for (int i = 0, size = indexes.size(); i < size; i++) { setObject(indexes.get(i), x, sqlType, scaleOrLength); } } } } return this; } /** * Sets the object. * * @param parameterName * @param x * @param type * @return * @throws SQLException the SQL exception */ public NamedQuery setObject(final String parameterName, final Object x, final Type type) throws SQLException { if (parameterCount < 5) { int cnt = 0; for (int i = 0; i < parameterCount; i++) { if (parameterNames.get(i).equals(parameterName)) { type.set(stmt, i + 1, x); cnt++; } } if (cnt == 0) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } } else { if (paramNameIndexMap == null) { initParamNameIndexMap(); } final IntList indexes = paramNameIndexMap.get(parameterName); if (indexes == null) { close(); throw new IllegalArgumentException("Not found named parameter: " + parameterName); } else { if (indexes.size() == 1) { type.set(stmt, indexes.get(0), x); } else if (indexes.size() == 2) { type.set(stmt, indexes.get(0), x); type.set(stmt, indexes.get(1), x); } else if (indexes.size() == 3) { type.set(stmt, indexes.get(0), x); type.set(stmt, indexes.get(1), x); type.set(stmt, indexes.get(2), x); } else { for (int i = 0, size = indexes.size(); i < size; i++) { type.set(stmt, indexes.get(i), x); } } } } return this; } /** * Sets the parameters. * * @param parameters * @return * @throws SQLException the SQL exception */ public NamedQuery setParameters(final Map parameters) throws SQLException { checkArgNotNull(parameters, "parameters"); for (String paramName : parameterNames) { if (parameters.containsKey(paramName)) { setObject(paramName, parameters.get(paramName)); } } return this; } /** * Sets the parameters. * * @param parameters with getter/setter methods * @return * @throws SQLException the SQL exception */ @SuppressWarnings("rawtypes") public NamedQuery setParameters(final Object parameters) throws SQLException { checkArgNotNull(parameters, "entity"); if (ClassUtil.isEntity(parameters.getClass())) { final Class cls = parameters.getClass(); final EntityInfo entityInfo = ParserUtil.getEntityInfo(cls); PropInfo propInfo = null; for (int i = 0; i < parameterCount; i++) { propInfo = entityInfo.getPropInfo(parameterNames.get(i)); if (propInfo != null) { propInfo.dbType.set(stmt, i + 1, propInfo.getPropValue(parameters)); } } } else if (parameters instanceof Map) { return setParameters((Map) parameters); } else if (parameters instanceof Collection) { return setParameters((Collection) parameters); } else if (parameters instanceof Object[]) { return setParameters((Object[]) parameters); } else if (parameters instanceof EntityId) { final EntityId entityId = (EntityId) parameters; for (String paramName : parameterNames) { if (entityId.containsKey(paramName)) { setObject(paramName, entityId.get(paramName)); } } } else if (parameterCount == 1) { setObject(1, parameters); } else { close(); throw new IllegalArgumentException("Unsupported named parameter type: " + parameters.getClass() + " for named sql: " + namedSQL.getNamedSQL()); } return this; } /** * Sets the parameters. * * @param * @param paramaters * @param parametersSetter * @return * @throws SQLException the SQL exception */ public NamedQuery setParameters(final T paramaters, TriParametersSetter parametersSetter) throws SQLException { checkArgNotNull(parametersSetter, "parametersSetter"); boolean noException = false; try { parametersSetter.accept(namedSQL, this, paramaters); noException = true; } finally { if (noException == false) { close(); } } return this; } /** * @param * @param batchParameters * @return * @throws SQLException the SQL exception */ public NamedQuery addBatchParameters(final Collection batchParameters) throws SQLException { checkArgNotNull(batchParameters, "batchParameters"); return addBatchParameters(batchParameters.iterator()); } /** * * @param * @param batchParameters * @return * @throws SQLException the SQL exception */ public NamedQuery addBatchParameters(final Iterator batchParameters) throws SQLException { checkArgNotNull(batchParameters, "batchParameters"); boolean noException = false; try { final Iterator iter = batchParameters; while (iter.hasNext()) { setParameters(iter.next()); stmt.addBatch(); isBatch = true; } noException = true; } finally { if (noException == false) { close(); } } return this; } } /** * The Enum FetchDirection. */ public enum FetchDirection { /** The forward. */ FORWARD(ResultSet.FETCH_FORWARD), /** The reverse. */ REVERSE(ResultSet.FETCH_REVERSE), /** The unknown. */ UNKNOWN(ResultSet.FETCH_UNKNOWN); /** The int value. */ private final int intValue; /** * Instantiates a new fetch direction. * * @param intValue */ FetchDirection(int intValue) { this.intValue = intValue; } /** * * @param intValue * @return */ public static FetchDirection valueOf(int intValue) { switch (intValue) { case ResultSet.FETCH_FORWARD: return FORWARD; case ResultSet.FETCH_REVERSE: return REVERSE; case ResultSet.FETCH_UNKNOWN: return UNKNOWN; default: throw new IllegalArgumentException("No FetchDirection mapping to int value: " + intValue); } } /** * * @return */ public int intValue() { return intValue; } } /** * The Interface ParametersSetter. * * @param */ public interface ParametersSetter extends Try.Consumer { @SuppressWarnings("rawtypes") public static final ParametersSetter DO_NOTHING = new ParametersSetter() { @Override public void accept(Object preparedQuery) throws SQLException { // Do nothing. } }; /** * * @param preparedQuery * @throws SQLException the SQL exception */ @Override void accept(QS preparedQuery) throws SQLException; } /** * The Interface BiParametersSetter. * * @param * @param */ public interface BiParametersSetter extends Try.BiConsumer { @SuppressWarnings("rawtypes") public static final BiParametersSetter DO_NOTHING = new BiParametersSetter() { @Override public void accept(Object preparedQuery, Object param) throws SQLException { // Do nothing. } }; /** * * @param preparedQuery * @param param * @throws SQLException the SQL exception */ @Override void accept(QS preparedQuery, T param) throws SQLException; } /** * The Interface TriParametersSetter. * * @param * @param */ public interface TriParametersSetter extends Try.TriConsumer { @SuppressWarnings("rawtypes") public static final TriParametersSetter DO_NOTHING = new TriParametersSetter() { @Override public void accept(NamedSQL namedSQL, Object preparedQuery, Object param) throws SQLException { // Do nothing. } }; /** * * @param namedSQL * @param preparedQuery * @param param * @throws SQLException the SQL exception */ @Override void accept(NamedSQL namedSQL, QS preparedQuery, T param) throws SQLException; } /** * The Interface ResultExtractor. * * @param */ public interface ResultExtractor extends Try.Function { /** The Constant TO_DATA_SET. */ ResultExtractor TO_DATA_SET = new ResultExtractor() { @Override public DataSet apply(final ResultSet rs) throws SQLException { return JdbcUtil.extractData(rs); } }; /** * * @param rs * @return * @throws SQLException the SQL exception */ @Override T apply(ResultSet rs) throws SQLException; /** * * @param the key type * @param the value type * @param keyExtractor * @param valueExtractor * @return */ static ResultExtractor> toMap(final RowMapper keyExtractor, final RowMapper valueExtractor) { return toMap(keyExtractor, valueExtractor, Suppliers. ofMap()); } /** * * @param the key type * @param the value type * @param * @param keyExtractor * @param valueExtractor * @param supplier * @return */ static > ResultExtractor toMap(final RowMapper keyExtractor, final RowMapper valueExtractor, final Supplier supplier) { return toMap(keyExtractor, valueExtractor, Fnn.throwingMerger(), supplier); } /** * * @param the key type * @param the value type * @param keyExtractor * @param valueExtractor * @param mergeFunction * @return * @see {@link Fn.EE#throwingMerger()} * @see {@link Fn.EE#replacingMerger()} * @see {@link Fn.EE#ignoringMerger()} */ static ResultExtractor> toMap(final RowMapper keyExtractor, final RowMapper valueExtractor, final Try.BinaryOperator mergeFunction) { return toMap(keyExtractor, valueExtractor, mergeFunction, Suppliers. ofMap()); } /** * * @param the key type * @param the value type * @param * @param keyExtractor * @param valueExtractor * @param mergeFunction * @param supplier * @return * @see {@link Fn.EE#throwingMerger()} * @see {@link Fn.EE#replacingMerger()} * @see {@link Fn.EE#ignoringMerger()} */ static > ResultExtractor toMap(final RowMapper keyExtractor, final RowMapper valueExtractor, final Try.BinaryOperator mergeFunction, final Supplier supplier) { N.checkArgNotNull(keyExtractor, "keyExtractor"); N.checkArgNotNull(valueExtractor, "valueExtractor"); N.checkArgNotNull(mergeFunction, "mergeFunction"); N.checkArgNotNull(supplier, "supplier"); return new ResultExtractor() { @Override public M apply(final ResultSet rs) throws SQLException { final M result = supplier.get(); while (rs.next()) { Maps.merge(result, keyExtractor.apply(rs), valueExtractor.apply(rs), mergeFunction); } return result; } }; } /** * * @param the key type * @param the value type * @param * @param * @param keyExtractor * @param valueExtractor * @param downstream * @return */ static ResultExtractor> toMap(final RowMapper keyExtractor, final RowMapper valueExtractor, final Collector downstream) { return toMap(keyExtractor, valueExtractor, downstream, Suppliers. ofMap()); } /** * * @param the key type * @param the value type * @param * @param * @param * @param keyExtractor * @param valueExtractor * @param downstream * @param supplier * @return */ static > ResultExtractor toMap(final RowMapper keyExtractor, final RowMapper valueExtractor, final Collector downstream, final Supplier supplier) { N.checkArgNotNull(keyExtractor, "keyExtractor"); N.checkArgNotNull(valueExtractor, "valueExtractor"); N.checkArgNotNull(downstream, "downstream"); N.checkArgNotNull(supplier, "supplier"); return new ResultExtractor() { @Override public M apply(final ResultSet rs) throws SQLException { final Supplier downstreamSupplier = downstream.supplier(); final BiConsumer downstreamAccumulator = downstream.accumulator(); final Function downstreamFinisher = downstream.finisher(); final M result = supplier.get(); final Map tmp = (Map) result; K key = null; A container = null; while (rs.next()) { key = keyExtractor.apply(rs); container = tmp.get(key); if (container == null) { container = downstreamSupplier.get(); tmp.put(key, container); } downstreamAccumulator.accept(container, valueExtractor.apply(rs)); } for (Map.Entry entry : result.entrySet()) { entry.setValue(downstreamFinisher.apply((A) entry.getValue())); } return result; } }; } /** * * @param the key type * @param the value type * @param keyExtractor * @param valueExtractor * @return * @throws SQLException the SQL exception */ static ResultExtractor>> groupTo(final RowMapper keyExtractor, final RowMapper valueExtractor) throws SQLException { return groupTo(keyExtractor, valueExtractor, Suppliers.> ofMap()); } /** * * @param the key type * @param the value type * @param * @param keyExtractor * @param valueExtractor * @param supplier * @return */ static >> ResultExtractor groupTo(final RowMapper keyExtractor, final RowMapper valueExtractor, final Supplier supplier) { N.checkArgNotNull(keyExtractor, "keyExtractor"); N.checkArgNotNull(valueExtractor, "valueExtractor"); N.checkArgNotNull(supplier, "supplier"); return new ResultExtractor() { @Override public M apply(final ResultSet rs) throws SQLException { final M result = supplier.get(); K key = null; List value = null; while (rs.next()) { key = keyExtractor.apply(rs); value = result.get(key); if (value == null) { value = new ArrayList<>(); result.put(key, value); } value.add(valueExtractor.apply(rs)); } return result; } }; } } /** * The Interface BiResultExtractor. * * @param */ public interface BiResultExtractor extends Try.BiFunction, T, SQLException> { /** * * @param rs * @param columnLabels * @return * @throws SQLException the SQL exception */ @Override T apply(ResultSet rs, List columnLabels) throws SQLException; /** * * @param the key type * @param the value type * @param keyExtractor * @param valueExtractor * @return */ static BiResultExtractor> toMap(final BiRowMapper keyExtractor, final BiRowMapper valueExtractor) { return toMap(keyExtractor, valueExtractor, Suppliers. ofMap()); } /** * * @param the key type * @param the value type * @param * @param keyExtractor * @param valueExtractor * @param supplier * @return */ static > BiResultExtractor toMap(final BiRowMapper keyExtractor, final BiRowMapper valueExtractor, final Supplier supplier) { return toMap(keyExtractor, valueExtractor, Fnn.throwingMerger(), supplier); } /** * * @param the key type * @param the value type * @param keyExtractor * @param valueExtractor * @param mergeFunction * @return * @see {@link Fn.EE#throwingMerger()} * @see {@link Fn.EE#replacingMerger()} * @see {@link Fn.EE#ignoringMerger()} */ static BiResultExtractor> toMap(final BiRowMapper keyExtractor, final BiRowMapper valueExtractor, final Try.BinaryOperator mergeFunction) { return toMap(keyExtractor, valueExtractor, mergeFunction, Suppliers. ofMap()); } /** * * @param the key type * @param the value type * @param * @param keyExtractor * @param valueExtractor * @param mergeFunction * @param supplier * @return * @see {@link Fn.EE#throwingMerger()} * @see {@link Fn.EE#replacingMerger()} * @see {@link Fn.EE#ignoringMerger()} */ static > BiResultExtractor toMap(final BiRowMapper keyExtractor, final BiRowMapper valueExtractor, final Try.BinaryOperator mergeFunction, final Supplier supplier) { N.checkArgNotNull(keyExtractor, "keyExtractor"); N.checkArgNotNull(valueExtractor, "valueExtractor"); N.checkArgNotNull(mergeFunction, "mergeFunction"); N.checkArgNotNull(supplier, "supplier"); return new BiResultExtractor() { @Override public M apply(final ResultSet rs, final List columnLabels) throws SQLException { final M result = supplier.get(); while (rs.next()) { Maps.merge(result, keyExtractor.apply(rs, columnLabels), valueExtractor.apply(rs, columnLabels), mergeFunction); } return result; } }; } /** * * @param the key type * @param the value type * @param * @param * @param keyExtractor * @param valueExtractor * @param downstream * @return */ static BiResultExtractor> toMap(final BiRowMapper keyExtractor, final BiRowMapper valueExtractor, final Collector downstream) { return toMap(keyExtractor, valueExtractor, downstream, Suppliers. ofMap()); } /** * * @param the key type * @param the value type * @param * @param * @param * @param keyExtractor * @param valueExtractor * @param downstream * @param supplier * @return */ static > BiResultExtractor toMap(final BiRowMapper keyExtractor, final BiRowMapper valueExtractor, final Collector downstream, final Supplier supplier) { N.checkArgNotNull(keyExtractor, "keyExtractor"); N.checkArgNotNull(valueExtractor, "valueExtractor"); N.checkArgNotNull(downstream, "downstream"); N.checkArgNotNull(supplier, "supplier"); return new BiResultExtractor() { @Override public M apply(final ResultSet rs, final List columnLabels) throws SQLException { final Supplier downstreamSupplier = downstream.supplier(); final BiConsumer downstreamAccumulator = downstream.accumulator(); final Function downstreamFinisher = downstream.finisher(); final M result = supplier.get(); final Map tmp = (Map) result; K key = null; A container = null; while (rs.next()) { key = keyExtractor.apply(rs, columnLabels); container = tmp.get(key); if (container == null) { container = downstreamSupplier.get(); tmp.put(key, container); } downstreamAccumulator.accept(container, valueExtractor.apply(rs, columnLabels)); } for (Map.Entry entry : result.entrySet()) { entry.setValue(downstreamFinisher.apply((A) entry.getValue())); } return result; } }; } /** * * @param the key type * @param the value type * @param keyExtractor * @param valueExtractor * @return * @throws SQLException the SQL exception */ static BiResultExtractor>> groupTo(final BiRowMapper keyExtractor, final BiRowMapper valueExtractor) throws SQLException { return groupTo(keyExtractor, valueExtractor, Suppliers.> ofMap()); } /** * * @param the key type * @param the value type * @param * @param keyExtractor * @param valueExtractor * @param supplier * @return */ static >> BiResultExtractor groupTo(final BiRowMapper keyExtractor, final BiRowMapper valueExtractor, final Supplier supplier) { N.checkArgNotNull(keyExtractor, "keyExtractor"); N.checkArgNotNull(valueExtractor, "valueExtractor"); N.checkArgNotNull(supplier, "supplier"); return new BiResultExtractor() { @Override public M apply(final ResultSet rs, List columnLabels) throws SQLException { final M result = supplier.get(); K key = null; List value = null; while (rs.next()) { key = keyExtractor.apply(rs, columnLabels); value = result.get(key); if (value == null) { value = new ArrayList<>(); result.put(key, value); } value.add(valueExtractor.apply(rs, columnLabels)); } return result; } }; } } /** The Constant NO_GENERATED_KEY_EXTRACTOR. */ static final RowMapper NO_GENERATED_KEY_EXTRACTOR = rs -> null; /** The Constant SINGLE_GENERATED_KEY_EXTRACTOR. */ static final RowMapper SINGLE_GENERATED_KEY_EXTRACTOR = rs -> getColumnValue(rs, 1); /** The Constant MULTI_GENERATED_KEY_EXTRACTOR. */ @SuppressWarnings("deprecation") static final RowMapper MULTI_GENERATED_KEY_EXTRACTOR = rs -> { final List columnLabels = JdbcUtil.getColumnLabelList(rs); if (columnLabels.size() == 1) { return getColumnValue(rs, 1); } else { final int columnCount = columnLabels.size(); final Seid id = Seid.of(N.EMPTY_STRING); for (int i = 1; i <= columnCount; i++) { id.set(columnLabels.get(i - 1), getColumnValue(rs, i)); } return id; } }; /** The Constant NO_BI_GENERATED_KEY_EXTRACTOR. */ static final BiRowMapper NO_BI_GENERATED_KEY_EXTRACTOR = (rs, columnLabels) -> null; /** The Constant SINGLE_BI_GENERATED_KEY_EXTRACTOR. */ static final BiRowMapper SINGLE_BI_GENERATED_KEY_EXTRACTOR = (rs, columnLabels) -> getColumnValue(rs, 1); /** The Constant MULTI_BI_GENERATED_KEY_EXTRACTOR. */ @SuppressWarnings("deprecation") static final BiRowMapper MULTI_BI_GENERATED_KEY_EXTRACTOR = (rs, columnLabels) -> { if (columnLabels.size() == 1) { return getColumnValue(rs, 1); } else { final int columnCount = columnLabels.size(); final Seid id = Seid.of(N.EMPTY_STRING); for (int i = 1; i <= columnCount; i++) { id.set(columnLabels.get(i - 1), getColumnValue(rs, i)); } return id; } }; @SuppressWarnings("rawtypes") private static final Map, RowMapper> singleGetRowMapperPool = new ObjectPool<>(1024); /** * Don't use {@code RowMapper} in {@link PreparedQuery#list(RowMapper)} or any place where multiple records will be retrieved by it, if column labels/count are used in {@link RowMapper#apply(ResultSet)}. * Consider using {@code BiRowMapper} instead because it's more efficient to retrieve multiple records when column labels/count are used. * * @param */ public interface RowMapper extends Try.Function { /** The Constant GET_BOOLEAN. */ RowMapper GET_BOOLEAN = new RowMapper() { @Override public Boolean apply(final ResultSet rs) throws SQLException { return rs.getBoolean(1); } }; /** The Constant GET_BYTE. */ RowMapper GET_BYTE = new RowMapper() { @Override public Byte apply(final ResultSet rs) throws SQLException { return rs.getByte(1); } }; /** The Constant GET_SHORT. */ RowMapper GET_SHORT = new RowMapper() { @Override public Short apply(final ResultSet rs) throws SQLException { return rs.getShort(1); } }; /** The Constant GET_INT. */ RowMapper GET_INT = new RowMapper() { @Override public Integer apply(final ResultSet rs) throws SQLException { return rs.getInt(1); } }; /** The Constant GET_LONG. */ RowMapper GET_LONG = new RowMapper() { @Override public Long apply(final ResultSet rs) throws SQLException { return rs.getLong(1); } }; /** The Constant GET_FLOAT. */ RowMapper GET_FLOAT = new RowMapper() { @Override public Float apply(final ResultSet rs) throws SQLException { return rs.getFloat(1); } }; /** The Constant GET_DOUBLE. */ RowMapper GET_DOUBLE = new RowMapper() { @Override public Double apply(final ResultSet rs) throws SQLException { return rs.getDouble(1); } }; /** The Constant GET_BIG_DECIMAL. */ RowMapper GET_BIG_DECIMAL = new RowMapper() { @Override public BigDecimal apply(final ResultSet rs) throws SQLException { return rs.getBigDecimal(1); } }; /** The Constant GET_STRING. */ RowMapper GET_STRING = new RowMapper() { @Override public String apply(final ResultSet rs) throws SQLException { return rs.getString(1); } }; /** The Constant GET_DATE. */ RowMapper GET_DATE = new RowMapper() { @Override public Date apply(final ResultSet rs) throws SQLException { return rs.getDate(1); } }; /** The Constant GET_TIME. */ RowMapper