diff --git a/.travis.yml b/.travis.yml index 055c1aa17..da3799985 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,9 +1,6 @@ sudo: required language: java -services: - - docker - jdk: - openjdk8 # - openjdk11 @@ -12,14 +9,6 @@ matrix: allow_failures: - jdk: openjdk11 -before_install: - # Disable services enabled by default - - sudo service mysql stop - - sudo /etc/init.d/postgresql stop - - # Run my databases in the background - - docker-compose -f docker/docker-compose-travis.yml up -d - install: - TERM=dumb ./gradlew assemble diff --git a/README.md b/README.md index 71c3905d3..fdb7b364e 100644 --- a/README.md +++ b/README.md @@ -21,9 +21,9 @@ Welcome to the **Jodd** - a unique, alternative world of Java :) You can find he Check the official web-site: https://jodd.org -## ‼️ The Future and Jodd Versions +## ‼️ The Future and Jodd Versions ‼️ -Version **v6** is the maintained version, working on Java 8 and 11. Only few components are promoted to v6: +Version **v6** is the maintained version, working on Java 8 and 11. the following components are promoted to v6: + [jodd-util](https://github.com/oblac/jodd-util) ⭐ + [jodd-mail](https://github.com/oblac/jodd-mail) ⭐ @@ -31,6 +31,9 @@ Version **v6** is the maintained version, working on Java 8 and 11. Only few com + [jodd-lagarto](https://github.com/oblac/jodd-lagarto) ⭐ + [jodd-http](https://github.com/oblac/jodd-http) ⭐ + [jodd-props](https://github.com/oblac/jodd-props) ⭐ ++ [jodd-petite](https://github.com/oblac/jodd-petite) ⭐ ++ [jodd-proxetta](https://github.com/oblac/jodd-proxetta) ⭐ ++ [jodd-db](https://github.com/oblac/jodd-db) ⭐ The decision which component is promoted is based on the Maven Central Repo statistics. @@ -54,10 +57,10 @@ _Use what you like._ **Thank you.** 🙏 **Micro-frameworks**: + `jodd-madvoc` - slick MVC framework. -+ `jodd-petite` - pragmatic DI container. -+ `jodd-proxetta` - dynamic proxies and `Paramo`. -+ `jodd-db` - thin database layer and object mapper. -+ `jodd-jtx` - transactions management. ++ `jodd-petite` - pragmatic DI container. ⭐ ++ `jodd-proxetta` - dynamic proxies and `Paramo`. ⭐ ++ `jodd-db` - thin database layer and object mapper. ⭐ ++ `jodd-jtx` - transactions management. ⭐ **Less used tools**: diff --git a/docker/docker-compose-test.yml b/docker/docker-compose-test.yml deleted file mode 100644 index 451cc7730..000000000 --- a/docker/docker-compose-test.yml +++ /dev/null @@ -1,25 +0,0 @@ -version: '2' -services: - - postgres: - image: postgres:9.4.4 - environment: - - POSTGRES_DB=jodd_test - - POSTGRES_USER=postgres - - POSTGRES_PASSWORD=root! - - LC_ALL=C.UTF-8 - ports: - - "5432:5432" - - mysql: - image: mysql:5.6 - environment: - - MYSQL_DATABASE=jodd_test - - MYSQL_ROOT_PASSWORD=root! - ports: - - "3306:3306" - - mssql: - build: mssql/. - ports: - - "1433:1433" diff --git a/docker/docker-compose-travis.yml b/docker/docker-compose-travis.yml deleted file mode 100644 index e086faa69..000000000 --- a/docker/docker-compose-travis.yml +++ /dev/null @@ -1,19 +0,0 @@ -version: '2' -services: - - postgres: - image: postgres:9.4.4 - environment: - - POSTGRES_DB=jodd_test - - POSTGRES_USER=postgres - - POSTGRES_PASSWORD=root! - - LC_ALL=C.UTF-8 - ports: - - "5432:5432" - mysql: - image: mysql:5.6 - environment: - - MYSQL_DATABASE=jodd_test - - MYSQL_ROOT_PASSWORD=root! - ports: - - "3306:3306" diff --git a/docker/mssql/Dockerfile b/docker/mssql/Dockerfile deleted file mode 100644 index b335e8419..000000000 --- a/docker/mssql/Dockerfile +++ /dev/null @@ -1,11 +0,0 @@ -FROM microsoft/mssql-server-linux - -ENV ACCEPT_EULA=Y -ENV SA_PASSWORD=root!R00t! - -COPY create-db.sql . -COPY create-db.sh . - -RUN chmod +x ./create-db.sh - -CMD /bin/bash ./create-db.sh \ No newline at end of file diff --git a/docker/mssql/create-db.sh b/docker/mssql/create-db.sh deleted file mode 100644 index d3cfd093b..000000000 --- a/docker/mssql/create-db.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/usr/bin/env bash - -set -e - -readonly run_cmd="/opt/mssql-tools/bin/sqlcmd -U sa -P 'root!R00t!' -l 30 -i create-db.sql" - ->&2 echo "Allowing 30 seconds for SQL Server to bootstrap, then creating database.." - -until $run_cmd -do - >&2 echo "This should not be executing!" -done \ No newline at end of file diff --git a/docker/mssql/create-db.sql b/docker/mssql/create-db.sql deleted file mode 100644 index 207a784e5..000000000 --- a/docker/mssql/create-db.sql +++ /dev/null @@ -1,7 +0,0 @@ -USE master -GO -IF EXISTS(SELECT * FROM sys.databases WHERE name='jodd_test') - DROP DATABASE jodd_test -GO -CREATE DATABASE jodd_test -GO \ No newline at end of file diff --git a/jodd-db/build.gradle b/jodd-db/build.gradle deleted file mode 100755 index 7472f9276..000000000 --- a/jodd-db/build.gradle +++ /dev/null @@ -1,22 +0,0 @@ - -ext.moduleName = 'Jodd DbOom' -ext.moduleDescription = 'Jodd DB is efficient and thin database facade; DbOom is convenient database object mapper.' - -apply plugin: 'kotlin' - -dependencies { - api project(':jodd-core') - api project(':jodd-jtx') - api 'org.jodd:jodd-props:6.0.1' - api 'org.slf4j:slf4j-api:1.7.30' - - testImplementation lib.junit5 - testImplementation lib.hsqldb - testImplementation lib.h2db - testImplementation lib.mysql - testImplementation lib.postgresql - testImplementation lib.mssql - testImplementation lib.mockito - testImplementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - testImplementation 'org.apache.commons:commons-lang3:3.9' -} diff --git a/jodd-db/src/main/java/jodd/db/DbCallResult.java b/jodd-db/src/main/java/jodd/db/DbCallResult.java deleted file mode 100755 index e31bc9819..000000000 --- a/jodd-db/src/main/java/jodd/db/DbCallResult.java +++ /dev/null @@ -1,300 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -package jodd.db; - -import java.sql.CallableStatement; -import java.sql.SQLException; - -/** - * Result of a CALL statement. - */ -public class DbCallResult { - private final DbQueryParser query; - private final CallableStatement statement; - - DbCallResult(final DbQueryParser parser, final CallableStatement callableStatement) { - this.query = parser; - this.statement = callableStatement; - } - - // ---------------------------------------------------------------- integer - - public int getInteger(final int index) { - try { - return statement.getInt(index); - } catch (SQLException sex) { - throw newGetParamError(index, sex); - } - } - - public int getInteger(final String param) { - final int[] positions = query.getNamedParameterIndices(param); - try { - if (positions.length == 1) { - return statement.getInt(positions[0]); - } - throw newGetParamError(param); - } catch (SQLException sex) { - throw newGetParamError(param, sex); - } - } - - public int[] getAllInteger(final String param) { - final int[] positions = query.getNamedParameterIndices(param); - final int[] result = new int[positions.length]; - try { - for (int i = 0; i < positions.length; i++) { - result[i] = statement.getInt(positions[i]); - } - return result; - } catch (SQLException sex) { - throw newGetParamError(param, sex); - } - } - - // ---------------------------------------------------------------- boolean - - public boolean getBoolean(final int index) { - try { - return statement.getBoolean(index); - } catch (SQLException sex) { - throw newGetParamError(index, sex); - } - } - - public boolean getBoolean(final String param) { - final int[] positions = query.getNamedParameterIndices(param); - try { - if (positions.length == 1) { - return statement.getBoolean(positions[0]); - } - throw newGetParamError(param); - } catch (SQLException sex) { - throw newGetParamError(param, sex); - } - } - - public boolean[] getAllBoolean(final String param) { - final int[] positions = query.getNamedParameterIndices(param); - final boolean[] result = new boolean[positions.length]; - try { - for (int i = 0; i < positions.length; i++) { - result[i] = statement.getBoolean(positions[i]); - } - return result; - } catch (SQLException sex) { - throw newGetParamError(param, sex); - } - } - - // ---------------------------------------------------------------- byte - - public byte getByte(final int index) { - try { - return statement.getByte(index); - } catch (SQLException sex) { - throw newGetParamError(index, sex); - } - } - - public byte getByte(final String param) { - final int[] positions = query.getNamedParameterIndices(param); - try { - if (positions.length == 1) { - return statement.getByte(positions[0]); - } - throw newGetParamError(param); - } catch (SQLException sex) { - throw newGetParamError(param, sex); - } - } - - public byte[] getAllByte(final String param) { - final int[] positions = query.getNamedParameterIndices(param); - final byte[] result = new byte[positions.length]; - try { - for (int i = 0; i < positions.length; i++) { - result[i] = statement.getByte(positions[i]); - } - return result; - } catch (SQLException sex) { - throw newGetParamError(param, sex); - } - } - - // ---------------------------------------------------------------- doublw - - public double getDouble(final int index) { - try { - return statement.getDouble(index); - } catch (SQLException sex) { - throw newGetParamError(index, sex); - } - } - - public double getDouble(final String param) { - final int[] positions = query.getNamedParameterIndices(param); - try { - if (positions.length == 1) { - return statement.getDouble(positions[0]); - } - throw newGetParamError(param); - } catch (SQLException sex) { - throw newGetParamError(param, sex); - } - } - - public double[] getAllDouble(final String param) { - final int[] positions = query.getNamedParameterIndices(param); - final double[] result = new double[positions.length]; - try { - for (int i = 0; i < positions.length; i++) { - result[i] = statement.getDouble(positions[i]); - } - return result; - } catch (SQLException sex) { - throw newGetParamError(param, sex); - } - } - - // ---------------------------------------------------------------- float - - public float getFloat(final int index) { - try { - return statement.getFloat(index); - } catch (SQLException sex) { - throw newGetParamError(index, sex); - } - } - - public float getFloat(final String param) { - final int[] positions = query.getNamedParameterIndices(param); - try { - if (positions.length == 1) { - return statement.getFloat(positions[0]); - } - throw newGetParamError(param); - } catch (SQLException sex) { - throw newGetParamError(param, sex); - } - } - - public float[] getAllFloat(final String param) { - final int[] positions = query.getNamedParameterIndices(param); - final float[] result = new float[positions.length]; - try { - for (int i = 0; i < positions.length; i++) { - result[i] = statement.getFloat(positions[i]); - } - return result; - } catch (SQLException sex) { - throw newGetParamError(param, sex); - } - } - - - // ---------------------------------------------------------------- string - - public String getString(final int index) { - try { - return statement.getString(index); - } catch (SQLException sex) { - throw newGetParamError(index, sex); - } - } - - public String getString(final String param) { - final int[] positions = query.getNamedParameterIndices(param); - try { - if (positions.length == 1) { - return statement.getString(positions[0]); - } - throw newGetParamError(param); - } catch (SQLException sex) { - throw newGetParamError(param, sex); - } - } - - public String[] getAllString(final String param) { - final int[] positions = query.getNamedParameterIndices(param); - final String[] result = new String[positions.length]; - try { - for (int i = 0; i < positions.length; i++) { - result[i] = statement.getString(positions[i]); - } - return result; - } catch (SQLException sex) { - throw newGetParamError(param, sex); - } - } - - // ---------------------------------------------------------------- long - - public long getLong(final int index) { - try { - return statement.getLong(index); - } catch (SQLException sex) { - throw newGetParamError(index, sex); - } - } - - public long getLong(final String param) { - final int[] positions = query.getNamedParameterIndices(param); - try { - if (positions.length == 1) { - return statement.getLong(positions[0]); - } - throw newGetParamError(param); - } catch (SQLException sex) { - throw newGetParamError(param, sex); - } - } - - public long[] getAllLong(final String param) { - final int[] positions = query.getNamedParameterIndices(param); - final long[] result = new long[positions.length]; - try { - for (int i = 0; i < positions.length; i++) { - result[i] = statement.getLong(positions[i]); - } - return result; - } catch (SQLException sex) { - throw newGetParamError(param, sex); - } - } - - // ---------------------------------------------------------------- exception - - private DbSqlException newGetParamError(final int index, final Exception ex) { - return new DbSqlException("Invalid SQL parameter with index: " + index, ex); - } - private DbSqlException newGetParamError(final String param, final Exception ex) { - return new DbSqlException("Invalid SQL parameter with name: " + param, ex); - } - private DbSqlException newGetParamError(final String param) { - return new DbSqlException("Invalid number of parameter with name: " + param); - } - -} diff --git a/jodd-db/src/main/java/jodd/db/DbDetector.java b/jodd-db/src/main/java/jodd/db/DbDetector.java deleted file mode 100644 index b34df4b85..000000000 --- a/jodd-db/src/main/java/jodd/db/DbDetector.java +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -package jodd.db; - -import jodd.db.connection.ConnectionProvider; -import jodd.db.oom.DbOomConfig; -import jodd.db.servers.Db2DbServer; -import jodd.db.servers.DbServer; -import jodd.db.servers.DerbyDbServer; -import jodd.db.servers.GenericDbServer; -import jodd.db.servers.HsqlDbServer; -import jodd.db.servers.InformixDbServer; -import jodd.db.servers.MySqlDbServer; -import jodd.db.servers.OracleDbServer; -import jodd.db.servers.PostgreSqlDbServer; -import jodd.db.servers.SQLiteDbServer; -import jodd.db.servers.SqlServerDbServer; -import jodd.db.servers.SybaseDbServer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.sql.Connection; -import java.sql.DatabaseMetaData; -import java.sql.SQLException; - -/** - * Database detector and DbOom configurator. - */ -public class DbDetector { - - private static final Logger log = LoggerFactory.getLogger(DbDetector.class); - - /** - * Detects database and configure DbOom engine. - */ - public DbServer detectDatabaseAndConfigureDbOom( - final ConnectionProvider cp, - final DbOomConfig dbOomConfig) { - - cp.init(); - - final Connection connection = cp.getConnection(); - - final DbServer dbServer = detectDatabase(connection); - - cp.closeConnection(connection); - - dbServer.accept(dbOomConfig); - - return dbServer; - } - - /** - * Detects database and returns {@link DbServer}. - */ - public DbServer detectDatabase(final Connection connection) { - final String dbName; - final int dbMajorVersion; - final String version; - - try { - log.info("Detecting database..."); - - final DatabaseMetaData databaseMetaData = connection.getMetaData(); - dbName = databaseMetaData.getDatabaseProductName(); - dbMajorVersion = databaseMetaData.getDatabaseMajorVersion(); - final int dbMinorVersion = databaseMetaData.getDatabaseMinorVersion(); - version = dbMajorVersion + "." + dbMinorVersion; - - log.info("Database: " + dbName + " v" + dbMajorVersion + "." + dbMinorVersion); - } - catch (final SQLException sex) { - final String msg = sex.getMessage(); - - if (msg.contains("explicitly set for database: DB2")) { - return new Db2DbServer(); - } - - throw new DbSqlException(sex); - } - - if (dbName.equals("Apache Derby")) { - return new DerbyDbServer(version); - } - if (dbName.startsWith("DB2/")) { - return new Db2DbServer(version); - } - if (dbName.equals("HSQL Database Engine")) { - return new HsqlDbServer(version); - } - if (dbName.equals("Informix Dynamic Server")) { - return new InformixDbServer(version); - } - if (dbName.startsWith("Microsoft SQL Server")) { - return new SqlServerDbServer(version); - } - if (dbName.equals("MySQL")) { - return new MySqlDbServer(version); - } - if (dbName.equals("Oracle")) { - return new OracleDbServer(version); - } - if (dbName.equals("PostgreSQL")) { - return new PostgreSqlDbServer(version); - } - if (dbName.equals("Sybase SQL Server")) { - return new SybaseDbServer(version); - } - if (dbName.equals("ASE") && (dbMajorVersion == 15)) { - return new SybaseDbServer(version); - } - if (dbName.equals("SQLite")) { - return new SQLiteDbServer(version); - } - - return new GenericDbServer(); - } -} diff --git a/jodd-db/src/main/java/jodd/db/DbOom.java b/jodd-db/src/main/java/jodd/db/DbOom.java deleted file mode 100644 index 0ce36564a..000000000 --- a/jodd-db/src/main/java/jodd/db/DbOom.java +++ /dev/null @@ -1,261 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db; - -import jodd.db.connection.ConnectionProvider; -import jodd.db.oom.DbEntityManager; -import jodd.db.oom.DbOomConfig; -import jodd.db.oom.DbOomQuery; -import jodd.db.oom.DbSqlGenerator; -import jodd.db.oom.sqlgen.DbEntitySql; -import jodd.db.oom.sqlgen.DbSqlBuilder; -import jodd.db.pool.CoreConnectionPool; -import jodd.db.querymap.EmptyQueryMap; -import jodd.db.querymap.QueryMap; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Starting class that all DBOOM starts from. - * It encapsulate the database and works like a factory for all - * db-related classes. This way you can have multiple connections. - */ -public class DbOom { - - private static final Logger log = LoggerFactory.getLogger(DbOom.class); - - /** - * The first DbOom is the default one, when only one is set. - * When you have two or more DbOom's the default dbOom is deregistered. - */ - private static DbOom defaultDbOom; - - /** - * Returns default DbOom instance. If multiple DbOoms are in use, - * an exception is thrown. - */ - public static DbOom get() { - if (defaultDbOom == null) { - throw new DbSqlException( - "No default DbOom available. Use DbOom to create one.\n" + - "If more then one DbOom is in use, there is no default instance."); - } - return defaultDbOom; - } - - // ---------------------------------------------------------------- builder - - /** - * Creates a new DbOom builder. - */ - public static Builder create() { - return new Builder(); - } - - public static class Builder { - private ConnectionProvider connectionProvider; - private DbSessionProvider dbSessionProvider; - private QueryMap queryMap; - - public Builder withSessionProvider(final DbSessionProvider sessionProvider) { - this.dbSessionProvider = sessionProvider; - return this; - } - - public Builder withConnectionProvider(final ConnectionProvider connectionProvider) { - this.connectionProvider = connectionProvider; - return this; - } - - public Builder withQueryMap(final QueryMap queryMap) { - this.queryMap = queryMap; - return this; - } - - /** - * Creates new DbOom. - */ - public DbOom get() { - if (connectionProvider == null) { - connectionProvider = new CoreConnectionPool(); - } - if (dbSessionProvider == null) { - dbSessionProvider = new ThreadDbSessionProvider(); - } - if (queryMap == null) { - queryMap = new EmptyQueryMap(); - } - return new DbOom(connectionProvider, dbSessionProvider, queryMap); - } - } - - private final ConnectionProvider connectionProvider; - private final DbSessionProvider dbSessionProvider; - private final QueryMap queryMap; - - private final DbQueryConfig dbQueryConfig; - private final DbOomConfig dbOomConfig; - private final DbEntityManager dbEntityManager; - private final DbEntitySql dbEntitySql; - - // ---------------------------------------------------------------- class - - /** - * Creates new DbOom. - */ - public DbOom( - final ConnectionProvider connectionProvider, - final DbSessionProvider dbSessionProvider, - final QueryMap queryMap) { - this.connectionProvider = connectionProvider; - this.dbSessionProvider = dbSessionProvider; - this.queryMap = queryMap; - - this.dbOomConfig = new DbOomConfig(); - this.dbQueryConfig = new DbQueryConfig(); - this.dbEntityManager = new DbEntityManager(dbOomConfig); - this.dbEntitySql = new DbEntitySql(this); - - // static init - - if (defaultDbOom == null) { - log.info("Default DbOom is created."); - defaultDbOom = this; - } - else { - log.warn("Multiple DbOom detected."); - defaultDbOom = null; - } - } - - /** - * Initializes the DbOom by connecting to the database. Database will be detected - * and DbOom will be configured to match it. - */ - public DbOom connect() { - connectionProvider.init(); - - final DbDetector dbDetector = new DbDetector(); - - dbDetector.detectDatabaseAndConfigureDbOom(connectionProvider, dbOomConfig); - - return this; - } - - /** - * Closes the DbOom. - */ - public void shutdown() { - if (defaultDbOom == this) { - defaultDbOom = null; - } - connectionProvider.close(); - } - - // ---------------------------------------------------------------- instances - - /** - * Returns DbOom configuration. - */ - public DbOomConfig config() { - return dbOomConfig; - } - - /** - * Returns default query configuration. - */ - public DbQueryConfig queryConfig() { - return dbQueryConfig; - } - - /** - * Returns DbOoom entity manager. - */ - public DbEntityManager entityManager() { - return dbEntityManager; - } - - /** - * Returns DbSession provider. - */ - public DbSessionProvider sessionProvider() { - return dbSessionProvider; - } - - /** - * Returns connection provider. - */ - public ConnectionProvider connectionProvider() { - return connectionProvider; - } - - /** - * Returns a query map. - */ - public QueryMap queryMap() { - return queryMap; - } - - // ---------------------------------------------------------------- entity - - /** - * Returns Entity SQL factory. - */ - public DbEntitySql entities() { - return dbEntitySql; - } - - // ---------------------------------------------------------------- factories - - /** - * Creates new T-SQL builder. - */ - public DbSqlBuilder sql(final String sql) { - return new DbSqlBuilder(this, sql); - } - - /** - * Creates new empty T-SQL builder. - */ - public DbSqlBuilder sql() { - return new DbSqlBuilder(this); - } - - /** - * Creates a query. - */ - public DbOomQuery query(final String sql) { - return new DbOomQuery(this, sessionProvider().getDbSession(), sql); - } - - /** - * Creates a query from a sql generator. - */ - public DbOomQuery query(final DbSqlGenerator sql) { - return new DbOomQuery(this, sessionProvider().getDbSession(), sql); - } - -} diff --git a/jodd-db/src/main/java/jodd/db/DbQuery.java b/jodd-db/src/main/java/jodd/db/DbQuery.java deleted file mode 100755 index e1220acd3..000000000 --- a/jodd-db/src/main/java/jodd/db/DbQuery.java +++ /dev/null @@ -1,1267 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db; - -import jodd.bean.BeanUtil; -import jodd.db.type.SqlType; -import jodd.db.type.SqlTypeManager; - -import java.io.IOException; -import java.io.InputStream; -import java.io.Reader; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.net.URL; -import java.sql.Array; -import java.sql.Blob; -import java.sql.Clob; -import java.sql.Connection; -import java.sql.Date; -import java.sql.Ref; -import java.sql.SQLException; -import java.sql.Statement; -import java.sql.Time; -import java.sql.Timestamp; -import java.sql.Types; -import java.util.Map; - -/** - * Encapsulates {@link Statement} and all its operations. - *
- * It may be: - *
- * Query life-cycle states: - *
extends DbQueryBase{ - - /** - * Creates new query. - */ - public DbQuery(final DbOom dbOom, final Connection conn, final String sqlString) { - super(dbOom); - this.connection = conn; - this.sqlString = sqlString; - } - - public static DbQuery query(final Connection conn, final String sqlString) { - return new DbQuery(DbOom.get(), conn, sqlString); - } - - /** - * Creates a new query from {@link DbSession}. - */ - public DbQuery(final DbOom dbOom, final DbSession session, final String sqlString) { - super(dbOom); - initSession(session); - this.session.attachQuery(this); - this.sqlString = sqlString; - } - - public static DbQuery query(final DbSession session, final String sqlString) { - return new DbQuery(DbOom.get(), session, sqlString); - } - - /** - * Creates a new query using default session provider. - */ - public DbQuery(final DbOom dbOom, final String sqlString) { - this(dbOom, (DbSession)null, sqlString); - } - - public static DbQuery query(final String sqlString) { - return new DbQuery(DbOom.get(), sqlString); - } - - - // ---------------------------------------------------------------- additional statement parameters - - /** - * Clears the current parameter values immediately. - *- * In general, parameter values remain in force for repeated use of a - * statement. Setting a parameter value automatically clears its - * previous value. However, in some cases it is useful to immediately - * release the resources used by the current parameter values; this can - * be done by calling the method
clearParameters
. - */ - public Q clearParameters() { - init(); - if (preparedStatement == null) { - return _this(); - } - try { - preparedStatement.clearParameters(); - } catch (SQLException sex) { - throw new DbSqlException(sex); - } - return _this(); - } - - - // ---------------------------------------------------------------- methods for setting statement parameters - - private void throwSetParamError(final int index, final Exception ex) { - throw new DbSqlException(this, "Invalid SQL parameter with index: " + index, ex); - } - - private void throwSetParamError(final String param, final Exception ex) { - throw new DbSqlException(this, "Invalid SQL parameter with name: " + param, ex); - } - - // ---------------------------------------------------------------- null - - public Q setNull(final int index, final int type) { - initPrepared(); - try { - preparedStatement.setNull(index, type); - } catch (SQLException sex) { - throw new DbSqlException(this, "Failed to set null to parameter: " + index, sex); - } - return _this(); - } - - public Q setNull(final String param, final int type) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setNull(position, type); - } - } catch (SQLException sex) { - throw new DbSqlException(this, "Failed to set null to parameter: " + param, sex); - } - return _this(); - } - - public Q setNull(final int index, final int type, final String typeName) { - initPrepared(); - try { - preparedStatement.setNull(index, type, typeName); - } catch (SQLException sex) { - throw new DbSqlException(this, "Failed to set null to parameter: " + index, sex); - } - return _this(); - } - - public Q setNull(final String param, final int value, final String typeName) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setNull(position, value, typeName); - } - } catch (SQLException sex) { - throw new DbSqlException(this, "Failed to set null to parameter: " + param, sex); - } - return _this(); - } - - // ---------------------------------------------------------------- int - - public Q setInteger(final int index, final int value) { - initPrepared(); - try { - preparedStatement.setInt(index, value); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setInteger(final String param, final int value) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setInt(position, value); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - public Q outInteger(final int index) { - return registerOutParameter(index, Types.INTEGER); - } - public Q outInteger(final String param) { - return registerOutParameter(param, Types.INTEGER); - } - - // ---------------------------------------------------------------- Integer - - public Q setInteger(final int index, final Number value) { - if (value == null) { - setNull(index, Types.INTEGER); - } - else { - setInteger(index, value.intValue()); - } - return _this(); - } - - public Q setInteger(final String param, final Number value) { - if (value == null) { - setNull(param, Types.INTEGER); - } - else { - setInteger(param, value.intValue()); - } - return _this(); - } - - // ---------------------------------------------------------------- boolean - - public Q setBoolean(final int index, final boolean value) { - initPrepared(); - try { - preparedStatement.setBoolean(index, value); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setBoolean(final String param, final boolean value) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setBoolean(position, value); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - public Q outBoolean(final int index) { - return registerOutParameter(index, Types.BOOLEAN); - } - public Q outBoolean(final String param) { - return registerOutParameter(param, Types.BOOLEAN); - } - - // ---------------------------------------------------------------- Boolean - - public Q setBoolean(final int index, final Boolean value) { - if (value == null) { - setNull(index, Types.BOOLEAN); - } - else { - setBoolean(index, value.booleanValue()); - } - return _this(); - } - - public Q setBoolean(final String param, final Boolean value) { - if (value == null) { - setNull(param, Types.BOOLEAN); - } - else { - setBoolean(param, value.booleanValue()); - } - return _this(); - } - - // ---------------------------------------------------------------- long - - public Q setLong(final int index, final long value) { - initPrepared(); - try { - preparedStatement.setLong(index, value); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setLong(final String param, final long value) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setLong(position, value); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - // ---------------------------------------------------------------- Long - - public Q setLong(final int index, final Number value) { - if (value == null) { - setNull(index, Types.BIGINT); - } - else { - setLong(index, value.longValue()); - } - return _this(); - } - - public Q setLong(final String param, final Number value) { - if (value == null) { - setNull(param, Types.BIGINT); - } - else { - setLong(param, value.longValue()); - } - return _this(); - } - - public Q outLong(final int index) { - return registerOutParameter(index, Types.BIGINT); - } - public Q outLong(final String param) { - return registerOutParameter(param, Types.BIGINT); - } - - // ---------------------------------------------------------------- byte - - public Q setByte(final int index, final byte value) { - initPrepared(); - try { - preparedStatement.setByte(index, value); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setByte(final String param, final byte value) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setByte(position, value); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - public Q outByte(final int index) { - return registerOutParameter(index, Types.SMALLINT); - } - public Q outByte(final String param) { - return registerOutParameter(param, Types.SMALLINT); - } - - // ---------------------------------------------------------------- Byte - - public Q setByte(final int index, final Number value) { - if (value == null) { - setNull(index, Types.SMALLINT); - } - else { - setByte(index, value.byteValue()); - } - return _this(); - } - - public Q setByte(final String param, final Number value) { - if (value == null) { - setNull(param, Types.SMALLINT); - } - else { - setByte(param, value.byteValue()); - } - return _this(); - } - - // ---------------------------------------------------------------- bytes[] - - public Q setBytes(final int index, final byte[] value) { - initPrepared(); - try { - preparedStatement.setBytes(index, value); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setBytes(final String param, final byte[] value) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setBytes(position, value); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - - // ---------------------------------------------------------------- double - - public Q setDouble(final int index, final double value) { - initPrepared(); - try { - preparedStatement.setDouble(index, value); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setDouble(final String param, final double value) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setDouble(position, value); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - public Q outDouble(final int index) { - return registerOutParameter(index, Types.DOUBLE); - } - public Q outDouble(final String param) { - return registerOutParameter(param, Types.DOUBLE); - } - - // ---------------------------------------------------------------- Double - - public Q setDouble(final int index, final Number value) { - if (value == null) { - setNull(index, Types.DOUBLE); - } - else { - setDouble(index, value.doubleValue()); - } - return _this(); - } - - public Q setDouble(final String param, final Number value) { - if (value == null) { - setNull(param, Types.DOUBLE); - } - else { - setDouble(param, value.doubleValue()); - } - return _this(); - } - - - // ---------------------------------------------------------------- float - - public Q setFloat(final int index, final float value) { - initPrepared(); - try { - preparedStatement.setFloat(index, value); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setFloat(final String param, final float value) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setFloat(position, value); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - public Q outFloat(final int index) { - return registerOutParameter(index, Types.FLOAT); - } - public Q outFloat(final String param) { - return registerOutParameter(param, Types.FLOAT); - } - - // ---------------------------------------------------------------- Float - - public Q setFloat(final int index, final Number value) { - if (value == null) { - setNull(index, Types.FLOAT); - } - else { - setFloat(index, value.floatValue()); - } - return _this(); - } - - public Q setFloat(final String param, final Number value) { - if (value == null) { - setNull(param, Types.FLOAT); - } - else { - setFloat(param, value.floatValue()); - } - return _this(); - } - - - // ---------------------------------------------------------------- short - - public Q setShort(final int index, final short value) { - initPrepared(); - try { - preparedStatement.setShort(index, value); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setShort(final String param, final short value) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - final int index = position; - preparedStatement.setShort(index, value); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - // ---------------------------------------------------------------- Short - - public Q setShort(final int index, final Number value) { - if (value == null) { - setNull(index, Types.SMALLINT); - } - else { - setShort(index, value.shortValue()); - } - return _this(); - } - - public Q setShort(final String param, final Number value) { - if (value == null) { - setNull(param, Types.SMALLINT); - } - else { - setShort(param, value.shortValue()); - } - return _this(); - } - - // ---------------------------------------------------------------- string - - public Q setString(final int index, final String value) { - initPrepared(); - try { - preparedStatement.setString(index, value); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setString(final String param, final String value) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setString(position, value); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - public Q outString(final int index) { - return registerOutParameter(index, Types.VARCHAR); - } - public Q outString(final String param) { - return registerOutParameter(param, Types.VARCHAR); - } - - - // ---------------------------------------------------------------- date - - public Q setDate(final int index, final Date value) { - initPrepared(); - try { - preparedStatement.setDate(index, value); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setDate(final String param, final Date value) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setDate(position, value); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - - // ---------------------------------------------------------------- time - - public Q setTime(final int index, final Time value) { - initPrepared(); - try { - preparedStatement.setTime(index, value); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setTime(final String param, final Time value) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setTime(position, value); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - // ---------------------------------------------------------------- timestamp - - public Q setTimestamp(final int index, final Timestamp value) { - initPrepared(); - try { - preparedStatement.setTimestamp(index, value); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setTimestamp(final String param, final Timestamp value) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setTimestamp(position, value); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - - // ---------------------------------------------------------------- big decimal - - public Q setBigDecimal(final int index, final BigDecimal value) { - initPrepared(); - try { - preparedStatement.setBigDecimal(index, value); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setBigDecimal(final String param, final BigDecimal value) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setBigDecimal(position, value); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - // ---------------------------------------------------------------- big integer - - public Q setBigInteger(final int index, final BigInteger value) { - if (value == null) { - setNull(index, Types.NUMERIC); - } - else { - setLong(index, value.longValue()); - } - return _this(); - } - - public Q setBigInteger(final String param, final BigInteger value) { - if (value == null) { - setNull(param, Types.NUMERIC); - } - else { - setLong(param, value.longValue()); - } - return _this(); - } - - - // ---------------------------------------------------------------- URL - - - public Q setURL(final int index, final URL value) { - initPrepared(); - try { - preparedStatement.setURL(index, value); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setURL(final String param, final URL value) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setURL(position, value); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - - // ---------------------------------------------------------------- BLOB - - public Q setBlob(final int index, final Blob value) { - initPrepared(); - try { - preparedStatement.setBlob(index, value); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setBlob(final String param, final Blob value) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setBlob(position, value); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - - // ---------------------------------------------------------------- CLOB - - public Q setClob(final int index, final Clob value) { - initPrepared(); - try { - preparedStatement.setClob(index, value); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setClob(final String param, final Clob value) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setClob(position, value); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - // ---------------------------------------------------------------- Array - - public Q setArray(final int index, final Array value) { - initPrepared(); - try { - preparedStatement.setArray(index, value); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setArray(final String param, final Array value) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setArray(position, value); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - - // ---------------------------------------------------------------- Ref - - public Q setRef(final int index, final Ref value) { - initPrepared(); - try { - preparedStatement.setRef(index, value); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setRef(final String param, final Ref value) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setRef(position, value); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - - // ---------------------------------------------------------------- ascii streams - - public Q setAsciiStream(final int index, final InputStream stream) { - initPrepared(); - try { - preparedStatement.setAsciiStream(index, stream, stream.available()); - } catch (IOException | SQLException ioex) { - throwSetParamError(index, ioex); - } - return _this(); - } - - public Q setAsciiStream(final String param, final InputStream stream) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setAsciiStream(position, stream, stream.available()); - } - } catch (IOException | SQLException ioex) { - throwSetParamError(param, ioex); - } - return _this(); - } - - public Q setAsciiStream(final int index, final InputStream stream, final int length) { - initPrepared(); - try { - preparedStatement.setAsciiStream(index, stream, length); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setAsciiStream(final String param, final InputStream stream, final int length) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setAsciiStream(position, stream, length); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - public Q setCharacterStream(final int index, final Reader reader, final int length) { - initPrepared(); - try { - preparedStatement.setCharacterStream(index, reader, length); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setCharacterStream(final String param, final Reader reader, final int length) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setCharacterStream(position, reader, length); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - - // ---------------------------------------------------------------- bean - - /** - * Sets bean parameters from bean. Non-existing bean properties are ignored. - */ - public Q setBean(final String beanName, final Object bean) { - if (bean == null) { - return _this(); - } - init(); - final String beanNamePrefix = beanName + '.'; - - query.forEachNamedParameter(p -> { - final String paramName = p.name; - - if (paramName.startsWith(beanNamePrefix)) { - final String propertyName = paramName.substring(beanNamePrefix.length()); - - if (BeanUtil.declared.hasRootProperty(bean, propertyName)) { - final Object value = BeanUtil.declared.getProperty(bean, propertyName); - setObject(paramName, value); - } - } - - }); - - return _this(); - } - - // ---------------------------------------------------------------- map - - /** - * Sets properties from the map. - */ - public Q setMap(final Map parameters) { - if (parameters == null) { - return _this(); - } - init(); - query.forEachNamedParameter(p -> { - final String paramName = p.name; - setObject(paramName, parameters.get(paramName)); - }); - return _this(); - } - - - // ---------------------------------------------------------------- objects - - /** - * Sets the value of the designated parameter with the given object. - * This method is like the methodsetObject
- * above, except that it assumes a scale of zero. - */ - public Q setObject(final int index, final Object object, final int targetSqlType) { - initPrepared(); - try { - preparedStatement.setObject(index, object, targetSqlType); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - /** - * Sets the value of the designated parameter with the given object. - * This method is like the methodsetObject
- * above, except that it assumes a scale of zero. - */ - public Q setObject(final String param, final Object object, final int targetSqlType) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setObject(position, object, targetSqlType); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - /** - * Sets the value of the designated parameter with the given object. - * This method is like the methodsetObject
- * above, except that it assumes a scale of zero. - */ - void setObject(final int index, final Object object, final int targetSqlType, final int scale) { - initPrepared(); - try { - preparedStatement.setObject(index, object, targetSqlType, scale); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - } - - /** - * Sets the value of the designated parameter with the given object. - * This method is like the methodsetObject
- * above, except that it assumes a scale of zero. - */ - void setObject(final String param, final Object object, final int targetSqlType, final int scale) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setObject(position, object, targetSqlType, scale); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - } - - - - // ---------------------------------------------------------------- object ex - - /** - * @see #setObject(String, Object, Class, int) - */ - public Q setObject(final int index, final Object value) { - setObject(index, value, null, Types.OTHER); - return _this(); - } - - /** - * Sets object parameter in an advanced way. - *- * First, it checks if object is
null
and invokessetNull
if so. - * If object is notnull
, it tries to resolve {@link SqlType sql type} (by looking up - * or using provided class) and use it for setting data. - * If sql type is not found, defaultsetObject
is invoked. - */ - @SuppressWarnings({"unchecked"}) - public Q setObject(final int index, final Object value, final Class extends SqlType> sqlTypeClass, final int dbSqlType) { - init(); - if (value == null) { - setNull(index, Types.NULL); - return _this(); - } - final SqlType sqlType; - if (sqlTypeClass != null) { - sqlType = SqlTypeManager.get().lookupSqlType(sqlTypeClass); - } else { - sqlType = SqlTypeManager.get().lookup(value.getClass()); - } - try { - if ((sqlType != null) && (dbSqlType != SqlType.DB_SQLTYPE_NOT_AVAILABLE)) { - sqlType.storeValue(preparedStatement, index, value, dbSqlType); - } else { - DbUtil.setPreparedStatementObject(preparedStatement, index, value, dbSqlType); - } - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - /** - * @see #setObject(String, Object, Class, int) - */ - public Q setObject(final String param, final Object value) { - setObject(param, value, null, Types.OTHER); - return _this(); - } - - /** - * @see #setObject(String, Object, Class, int) - */ - public Q setObject(final String param, final Object value, final Class extends SqlType> sqlTypeClass, final int dbSqlType) { - init(); - final int[] positions = query.getNamedParameterIndices(param); - for (final int position : positions) { - setObject(position, value, sqlTypeClass, dbSqlType); - } - return _this(); - } - - - // ---------------------------------------------------------------- set object shortcuts - - /** - * Sets an array of objects parameters in given order. - */ - public Q setObjects(final Object... objects) { - int index = 1; - for (final Object object : objects) { - setObject(index++, object); - } - return _this(); - } - - /** - * Sets sql parameters from two arrays: names and values. - */ - public Q setObjects(final String[] names, final Object[] values) { - init(); - if (names.length != values.length) { - throw new DbSqlException(this, "Different number of parameter names and values"); - } - for (int i = 0; i < names.length; i++) { - setObject(names[i], values[i]); - } - return _this(); - } - - // ---------------------------------------------------------------- batch - - /** - * Sets batch parameters with given array of values. - */ - public Q setBatch(final String name, final int[] array, int startingIndex) { - init(); - final int batchSize = query.getBatchParameterSize(name); - - for (int i = 1; i <= batchSize; i++) { - final String paramName = name + '.' + i; - - if (startingIndex < array.length) { - setInteger(paramName, array[startingIndex]); - } else { - setNull(paramName, Types.INTEGER); - } - startingIndex++; - } - return _this(); - } - /** - * Sets batch parameters with given array of values. - */ - public Q setBatch(final String name, final long[] array, int startingIndex) { - init(); - final int batchSize = query.getBatchParameterSize(name); - - for (int i = 1; i <= batchSize; i++) { - final String paramName = name + '.' + i; - - if (startingIndex < array.length) { - setLong(paramName, array[startingIndex]); - } else { - setNull(paramName, Types.INTEGER); - } - startingIndex++; - } - return _this(); - } - - /** - * Sets batch parameters with given array of values. - */ - public Q setBatch(final String name, final Object[] array, int startingIndex) { - init(); - final int batchSize = query.getBatchParameterSize(name); - - for (int i = 1; i <= batchSize; i++) { - final String paramName = name + '.' + i; - - if (startingIndex < array.length) { - setObject(paramName, array[startingIndex]); - } else { - setObject(paramName, null); - } - startingIndex++; - } - return _this(); - } - - // ---------------------------------------------------------------- utils - - private void initPrepared() { - init(); - if (preparedStatement == null) { - throw new DbSqlException("Prepared statement not initialized."); - } - } - private void initCallable() { - init(); - if (callableStatement == null) { - throw new DbSqlException("Callable statement not initialized."); - } - } - - private Q registerOutParameter(final int index, final int type) { - initCallable(); - try { - callableStatement.registerOutParameter(index,type); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - private Q registerOutParameter(final String param, final int type) { - initCallable(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - callableStatement.registerOutParameter(position, type); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - // ---------------------------------------------------------------- close - - /** - * {@inheritDoc} - */ - @Override - public Q autoClose() { - super.autoClose(); - return _this(); - } - -} diff --git a/jodd-db/src/main/java/jodd/db/DbQueryBase.java b/jodd-db/src/main/java/jodd/db/DbQueryBase.java deleted file mode 100644 index 8368eab00..000000000 --- a/jodd-db/src/main/java/jodd/db/DbQueryBase.java +++ /dev/null @@ -1,1004 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db; - -import jodd.db.debug.LoggableCallableStatement; -import jodd.db.debug.LoggablePreparedStatement; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.sql.CallableStatement; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import static jodd.db.DbQueryBase.State.CLOSED; -import static jodd.db.DbQueryBase.State.CREATED; -import static jodd.db.DbQueryBase.State.INITIALIZED; - -/** - * Support for {@link DbQuery} holds all configuration, initialization and the execution code. - */ -abstract class DbQueryBaseimplements AutoCloseable { - - private static final Logger log = LoggerFactory.getLogger(DbQueryBase.class); - - protected final DbOom dbOom; - - // ---------------------------------------------------------------- ctor - - protected DbQueryBase(final DbOom dbOom) { - this.dbOom = dbOom; - this.forcePreparedStatement = dbOom.queryConfig().isForcePreparedStatement(); - this.type = dbOom.queryConfig().getType(); - this.concurrencyType = dbOom.queryConfig().getConcurrencyType(); - this.holdability = dbOom.queryConfig().getHoldability(); - this.debug = dbOom.queryConfig().isDebug(); - this.fetchSize = dbOom.queryConfig().getFetchSize(); - this.maxRows = dbOom.queryConfig().getMaxRows(); - } - - @SuppressWarnings("unchecked") - protected Q _this() { - return (Q) this; - } - - - // ---------------------------------------------------------------- query states - - /** - * Query states. - */ - public enum State { - CREATED, INITIALIZED, CLOSED - } - protected State queryState = CREATED; - - /** - * Returns query state. - */ - public State getQueryState() { - return queryState; - } - - /** - * Checks if query is not closed and throws an exception if it is. - */ - protected void checkNotClosed() { - if (queryState == CLOSED) { - throw new DbSqlException(this, "Query is closed. Operation may be performed only on active queries."); - } - } - - /** - * Checks if query is created (and not yet initialized or closed) and throws an exception if it is not. - */ - protected void checkCreated() { - if (queryState != CREATED) { - final String message = (queryState == INITIALIZED ? - "Query is already initialized." : "Query is closed."); - throw new DbSqlException(this, message + " Operation may be performed only on created queries."); - } - } - - /** - * Checks if query is initialized and throws an exception if it is not. - */ - protected void checkInitialized() { - if (queryState != INITIALIZED) { - final String message = (queryState == CREATED ? - "Query is created but not yet initialized." : "Query is closed."); - throw new DbSqlException(this, message + " Operation may be performed only on initialized queries."); - } - } - - - - /** - * Returnstrue
if query is closed. - */ - public boolean isClosed() { - return queryState == CLOSED; - } - - /** - * Returnstrue
if query is active: created and possibly initialized. - * Opened query may be not initialized. - */ - public boolean isActive() { - return queryState != CLOSED; - } - - /** - * Returnstrue
if query is initialized. Initialized query is the one that has - * created JDBC statements. - */ - public boolean isInitialized() { - return queryState == INITIALIZED; - } - - // ---------------------------------------------------------------- input - - protected Connection connection; - protected DbSession session; - protected String sqlString; - - /** - * Returns used {@link DbSession}. - */ - public DbSession getSession() { - return session; - } - - // ---------------------------------------------------------------- statement - - protected Statement statement; - protected PreparedStatement preparedStatement; - protected CallableStatement callableStatement; - protected SetresultSets; - protected DbQueryParser query; - - /** - * Stores result set. - */ - protected void saveResultSet(final ResultSet rs) { - if (resultSets == null) { - resultSets = new HashSet<>(); - } - resultSets.add(rs); - } - - // ---------------------------------------------------------------- configuration - - /** - * If set to true
all created statements will be prepared. - */ - protected boolean forcePreparedStatement; - - /** - * Forces creation of prepared statements. - */ - public Q forcePreparedStatement() { - checkCreated(); - forcePreparedStatement = true; - return _this(); - } - - // ---------------------------------------------------------------- initialization - - /** - * Initializes the query if not already initialized. - * Usually, user doesn't have to invoke it at all, since it will - * be called before all methods that deals directly with JDBC statement. - * Throws an exception if called on closed query. - */ - public final void init() { - checkNotClosed(); - if (queryState == INITIALIZED) { - return; - } - initializeJdbc(); - queryState = INITIALIZED; - prepareQuery(); - } - - /** - * Initializes session. When not specified (i.e. isnull
), - * session is fetched from session provider. - */ - protected void initSession(final DbSession session) { - if (session != null) { - this.session = session; - return; - } - - final DbSessionProvider dbSessionProvider = dbOom.sessionProvider(); - - this.session = dbSessionProvider.getDbSession(); - } - - /** - * Performs JDBC initialization of the query. Obtains connection, parses the SQL query string - * and creates statements. Initialization is performed only once, when switching to initialized state. - */ - @SuppressWarnings("MagicConstant") - protected void initializeJdbc() { - // connection - if (connection == null) { - initSession(session); - - connection = session.getConnection(); - } - - this.query = new DbQueryParser(sqlString); - - // callable statement - - if (query.callable) { - try { - if (debug) { - if (holdability != QueryHoldability.DEFAULT) { - callableStatement = new LoggableCallableStatement( - connection.prepareCall(query.sql, type.value(), concurrencyType.value(), holdability.value()), - query.sql - ); - } else { - callableStatement = new LoggableCallableStatement( - connection.prepareCall(query.sql, type.value(), concurrencyType.value()), - query.sql - ); - } - } - else { - if (holdability != QueryHoldability.DEFAULT) { - callableStatement = connection.prepareCall( - query.sql, type.value(), concurrencyType.value(), holdability.value()); - } else { - callableStatement = connection.prepareCall( - query.sql, type.value(), concurrencyType.value()); - } - } - } - catch (final SQLException sex) { - throw new DbSqlException(this, "Error creating callable statement", sex); - } - - preparedStatement = callableStatement; - statement = callableStatement; - - return; - } - - // prepared statement - - if (query.prepared || forcePreparedStatement) { - try { - if (debug) { - if (generatedColumns != null) { - if (generatedColumns.length == 0) { - preparedStatement = new LoggablePreparedStatement( - connection.prepareStatement(query.sql, Statement.RETURN_GENERATED_KEYS), - query.sql); - } else { - preparedStatement = new LoggablePreparedStatement( - connection.prepareStatement(query.sql, generatedColumns), - query.sql); - } - } else { - if (holdability != QueryHoldability.DEFAULT) { - preparedStatement = new LoggablePreparedStatement( - connection.prepareStatement(query.sql, type.value(), concurrencyType.value(), holdability.value()), - query.sql); - } else { - preparedStatement = new LoggablePreparedStatement( - connection.prepareStatement(query.sql, type.value(), concurrencyType.value()), - query.sql); - } - } - } else { - if (generatedColumns != null) { - if (generatedColumns.length == 0) { - preparedStatement = connection.prepareStatement(query.sql, Statement.RETURN_GENERATED_KEYS); - } else { - preparedStatement = connection.prepareStatement(query.sql, generatedColumns); - } - } else { - if (holdability != QueryHoldability.DEFAULT) { - preparedStatement = connection.prepareStatement( - query.sql, type.value(), concurrencyType.value(), holdability.value()); - } else { - preparedStatement = connection.prepareStatement( - query.sql, type.value(), concurrencyType.value()); - } - } - } - } - catch (final SQLException sex) { - throw new DbSqlException(this, "Error creating prepared statement", sex); - } - - statement = preparedStatement; - - return; - } - - // statement - - try { - if (holdability != QueryHoldability.DEFAULT) { - statement = connection.createStatement(type.value(), concurrencyType.value(), holdability.value()); - } else { - statement = connection.createStatement(type.value(), concurrencyType.value()); - } - } catch (final SQLException sex) { - throw new DbSqlException(this, "Error creating statement", sex); - } - } - - /** - * Prepares the query just after the initialization. - * Query is fully set and ready. - */ - protected void prepareQuery() { - if (fetchSize != 0) { - setFetchSize(fetchSize); - } - if (maxRows != 0) { - setMaxRows(maxRows); - } - } - - - // ---------------------------------------------------------------- close - - protected boolean autoClose; - - /** - * Defines that query should be automatically closed immediately after using. - * Should be called before actual statement execution. - */ - public Q autoClose() { - autoClose = true; - return _this(); - } - - /** - * Closes all result sets opened by this query. Query remains active. - * ReturnsSQLException
(stacked with all exceptions) - * ornull
. - */ - private SQLException closeQueryResultSets() { - SQLException sqlException = null; - - if (resultSets != null) { - for (final ResultSet rs : resultSets) { - try { - rs.close(); - } catch (final SQLException sex) { - if (sqlException == null) { - sqlException = sex; - } else { - sqlException.setNextException(sex); - } - } finally { - totalOpenResultSetCount--; - } - } - resultSets.clear(); - resultSets = null; - } - return sqlException; - } - - /** - * Closes all result sets created by this query. Query remains active. - */ - public Q closeAllResultSets() { - final SQLException sex = closeQueryResultSets(); - if (sex != null) { - throw new DbSqlException("Close associated ResultSets error", sex); - } - return _this(); - } - - /** - * Closes all assigned result sets and then closes the query. Query becomes closed. - */ - protected SQLException closeQuery() { - SQLException sqlException = closeQueryResultSets(); - if (statement != null) { - try { - statement.close(); - } catch (final SQLException sex) { - if (sqlException == null) { - sqlException = sex; - } else { - sqlException.setNextException(sex); - } - } - statement = null; - } - query = null; - queryState = CLOSED; - return sqlException; - } - - /** - * Closes the query and all created results sets and detaches itself from the session. - */ - @Override - @SuppressWarnings({"ClassReferencesSubclass"}) - public void close() { - final SQLException sqlException = closeQuery(); - connection = null; - if (this.session != null) { - this.session.detachQuery(this); - } - if (sqlException != null) { - throw new DbSqlException("Close query error", sqlException); - } - } - - /** - * Closes single result set that was created by this query. It is not necessary to close result sets - * explicitly, since {@link DbQueryBase#close()} method closes all created result sets. - * Query remains active. - */ - public void closeResultSet(final ResultSet rs) { - if (rs == null) { - return; - } - if (!resultSets.remove(rs)) { - throw new DbSqlException(this, "ResultSet is not created by this query"); - } - try { - rs.close(); - } catch (final SQLException sex) { - throw new DbSqlException(this, "Close result set error", sex); - } finally { - totalOpenResultSetCount--; - } - } - - // ---------------------------------------------------------------- result set type - - protected QueryScrollType type; - - public QueryScrollType getType() { - return type; - } - - public Q setType(final QueryScrollType type) { - checkCreated(); - this.type = type; - return _this(); - } - public Q typeForwardOnly() { - setType(QueryScrollType.FORWARD_ONLY); - return _this(); - } - public Q typeScrollSensitive() { - setType(QueryScrollType.SCROLL_SENSITIVE); - return _this(); - } - public Q typeScrollInsensitive() { - setType(QueryScrollType.SCROLL_INSENSITIVE); - return _this(); - } - - // ---------------------------------------------------------------- concurrency - - protected QueryConcurrencyType concurrencyType; - - public QueryConcurrencyType getConcurrencyType() { - return concurrencyType; - } - - public Q setConcurrencyType(final QueryConcurrencyType concurrencyType) { - checkCreated(); - this.concurrencyType = concurrencyType; - return _this(); - } - public Q concurrentReadOnly() { - setConcurrencyType(QueryConcurrencyType.READ_ONLY); - return _this(); - } - public Q concurrentUpdatable() { - setConcurrencyType(QueryConcurrencyType.UPDATABLE); - return _this(); - } - - // ---------------------------------------------------------------- holdability - - protected QueryHoldability holdability; - - public QueryHoldability getHoldability() { - return holdability; - } - - public Q setHoldability(final QueryHoldability holdability) { - checkCreated(); - this.holdability = holdability; - return _this(); - } - - public Q holdCursorsOverCommit() { - setHoldability(QueryHoldability.HOLD_CURSORS_OVER_COMMIT); - return _this(); - } - - public Q closeCursorsAtCommit() { - setHoldability(QueryHoldability.CLOSE_CURSORS_AT_COMMIT); - return _this(); - } - - // ---------------------------------------------------------------- debug mode - - protected boolean debug; - - public boolean isInDebugMode() { - return debug; - } - - public Q setDebug(final boolean debug) { - checkCreated(); - this.debug = debug; - return _this(); - } - public Q setDebugMode() { - setDebug(true); - return _this(); - } - - - // ---------------------------------------------------------------- generated keys - - protected String[] generatedColumns; - - /** - * Returns generated column names. - */ - public String[] getGeneratedColumnNames() { - return generatedColumns; - } - - /** - * Specifies columns which values will be generated by database. - */ - public Q setGeneratedColumns(final String... columns) { - checkCreated(); - generatedColumns = columns; - return _this(); - } - - /** - * Specifies that database will generate some columns values, - * usually the single id. - */ - public Q setGeneratedKey() { - setGeneratedColumns(); - return _this(); - } - - /** - * Resets creating generated columns. - */ - public Q resetGeneratedColumns() { - checkCreated(); - generatedColumns = null; - return _this(); - } - - - // ---------------------------------------------------------------- performance hints - - protected int fetchSize; - - /** - * Returns fetch size. - * @see #setFetchSize(int) - */ - public int getFetchSize() { - return fetchSize; - } - - /** - * Gives the JDBC driver a hint as to the number of rows that should be fetched from the database when - * more rows are needed. The number of rows specified affects only result sets created using this statement. - * If the value specified is zero, then the hint is ignored. The default value is zero. - * @see Statement#setFetchSize(int) - */ - public Q setFetchSize(final int rows) { - checkNotClosed(); - this.fetchSize = rows; - if (statement != null) { - try { - statement.setFetchSize(fetchSize); - } catch (final SQLException sex) { - throw new DbSqlException(this, "Unable to set fetch size: " + fetchSize, sex); - } - } - return _this(); - } - - protected int maxRows; - - /** - * Returns max rows. - * @see #setMaxRows(int) - */ - public int getMaxRows() { - return maxRows; - } - - /** - * Sets the limit for the maximum number of rows that any ResultSet object can contain to the given number. - * If the limit is exceeded, the excess rows are silently dropped. Zero means there is no limit. - * @see Statement#setMaxRows(int) - */ - public Q setMaxRows(final int maxRows) { - checkNotClosed(); - this.maxRows = maxRows; - if (statement != null) { - try { - statement.setMaxRows(maxRows); - } catch (final SQLException sex) { - throw new DbSqlException(this, "Unable to set max rows: " + maxRows, sex); - } - } - return _this(); - } - - // ---------------------------------------------------------------- execute - protected long start; - protected long elapsed = -1; - - /** - * Returns query execution elapsed time in milliseconds. - * Returns-1
if query is still not executed. - */ - public long getExecutionTime() { - return elapsed; - } - - /** - * Executes the query. If this method is invoked at least once, the query or - * all created ResultSets must be explicitly closed at the end of query usage. - * This can be done explicitly by calling {@link DbQueryBase#closeResultSet(ResultSet)} - * оr implicitly, during {@link DbQueryBase#close()}. - * @see Statement#execute(String) - */ - public ResultSet execute() { - start = System.currentTimeMillis(); - - init(); - ResultSet rs = null; - if (log.isDebugEnabled()) { - log.debug("Executing statement: " + getQueryString()); - } - try { - if (preparedStatement == null) { - rs = statement.executeQuery(query.sql); - } else { - rs = preparedStatement.executeQuery(); - } - rs.setFetchSize(fetchSize); - } catch (final SQLException sex) { - DbUtil.close(rs); - throw new DbSqlException(this, "Query execution failed", sex); - } - saveResultSet(rs); - totalOpenResultSetCount++; - - elapsed = System.currentTimeMillis() - start; - if (log.isDebugEnabled()) { - log.debug("execution time: " + elapsed + "ms"); - } - return rs; - } - - public DbCallResult executeCall() { - start = System.currentTimeMillis(); - - init(); - if (log.isDebugEnabled()) { - log.debug("Calling statement: " + getQueryString()); - } - try { - callableStatement.execute(); - } catch (final SQLException sex) { - DbUtil.close(callableStatement); - throw new DbSqlException(this, "Query execution failed", sex); - } - - elapsed = System.currentTimeMillis() - start; - if (log.isDebugEnabled()) { - log.debug("execution time: " + elapsed + "ms"); - } - return new DbCallResult(query, callableStatement); - } - - /** - * Executes UPDATE, INSERT or DELETE queries. Query is not closed afterwards - * unless {@link #autoClose() auto close mode} is set. - * @see Statement#executeUpdate(String) - */ - public int executeUpdate() { - return executeUpdate(autoClose); - } - - /** - * Executes UPDATE, INSERT or DELETE queries and optionally closes the query. - * @see Statement#executeUpdate(String) - */ - protected int executeUpdate(final boolean closeQuery) { - start = System.currentTimeMillis(); - - init(); - final int result; - if (log.isDebugEnabled()) { - log.debug("Executing update: " + getQueryString()); - } - try { - if (preparedStatement == null) { - if (generatedColumns != null) { - if (generatedColumns.length == 0) { - result = statement.executeUpdate(query.sql, Statement.RETURN_GENERATED_KEYS); - } else { - result = statement.executeUpdate(query.sql, generatedColumns); - } - } else { - result = statement.executeUpdate(query.sql); - } - } else { - result = preparedStatement.executeUpdate(); - } - } catch (final SQLException sex) { - throw new DbSqlException(this, "Query execution failed", sex); - } - if (closeQuery) { - close(); - } - - elapsed = System.currentTimeMillis() - start; - if (log.isDebugEnabled()) { - log.debug("execution time: " + elapsed + "ms"); - } - return result; - } - - /** - * Special execute() for 'select count(*)' queries. Query is not closed after the execution - * unless {@link #autoClose() auto-close mode} is set. - * Doesn't check if query is really a count query, so it would work for any - * query that has number in the first column of result. - * If result set returns zero rows (very unlikely), returns-1
. - */ - public long executeCount() { - return executeCount(autoClose); - } - - /** - * Executes count queries and optionally closes query afterwards. - */ - protected long executeCount(final boolean close) { - start = System.currentTimeMillis(); - - init(); - ResultSet rs = null; - if (log.isDebugEnabled()) { - log.debug("Executing prepared count: " + getQueryString()); - } - try { - if (preparedStatement == null) { - rs = statement.executeQuery(query.sql); - } else { - rs = preparedStatement.executeQuery(); - } - - final long firstLong = DbUtil.getFirstLong(rs); - - elapsed = System.currentTimeMillis() - start; - if (log.isDebugEnabled()) { - log.debug("execution time: " + elapsed + "ms"); - } - - return firstLong; - } catch (final SQLException sex) { - throw new DbSqlException(this, "Count query failed", sex); - } finally { - DbUtil.close(rs); - if (close) { - close(); - } - } - } - - // ---------------------------------------------------------------- result set mapper - - /** - * {@link #execute() Executes} the query, iterates result set and - * {@link QueryMapper maps} each row. - */ - publicList list(final QueryMapper queryMapper) { - final ResultSet resultSet = execute(); - - final List list = new ArrayList<>(); - - try { - while (resultSet.next()) { - final T t = queryMapper.process(resultSet); - if (t == null) { - break; - } - list.add(t); - } - } catch (final SQLException sex) { - throw new DbSqlException(sex); - } finally { - DbUtil.close(resultSet); - } - - return list; - } - - /** - * {@link #execute() Executes} the query and {@link QueryMapper maps} single result row. - */ - public T find(final QueryMapper queryMapper) { - final ResultSet resultSet = execute(); - - try { - if (resultSet.next()) { - return queryMapper.process(resultSet); - } - } catch (final SQLException sex) { - throw new DbSqlException(sex); - } finally { - DbUtil.close(resultSet); - } - return null; - } - - /** - * {@link #execute() Executes} the query, iterates all rows and - * {@link QueryMapper maps} them. - */ - public Set listSet(final QueryMapper queryMapper) { - final ResultSet resultSet = execute(); - - final Set set = new HashSet<>(); - - try { - while (resultSet.next()) { - final T t = queryMapper.process(resultSet); - if (t == null) { - break; - } - set.add(t); - } - } catch (final SQLException sex) { - throw new DbSqlException(sex); - } finally { - DbUtil.close(resultSet); - } - return set; - } - - // ---------------------------------------------------------------- generated keys - - /** - * Returns generated columns. - */ - public ResultSet getGeneratedColumns() { - checkInitialized(); - if (generatedColumns == null) { - throw new DbSqlException(this, "No column is specified as auto-generated"); - } - final ResultSet rs; - try { - rs = statement.getGeneratedKeys(); - } catch (final SQLException sex) { - throw new DbSqlException(this, "No generated keys", sex); - } - saveResultSet(rs); - totalOpenResultSetCount++; - return rs; - } - - /** - * Returns generated key i.e. first generated column as long
. - */ - public long getGeneratedKey() { - checkInitialized(); - final ResultSet rs = getGeneratedColumns(); - try { - return DbUtil.getFirstLong(rs); - } catch (final SQLException sex) { - throw new DbSqlException(this, "No generated key as long", sex); - } finally { - DbUtil.close(rs); - resultSets.remove(rs); - totalOpenResultSetCount--; - } - } - - public Object getGeneratedKeyObject() { - checkInitialized(); - final ResultSet rs = getGeneratedColumns(); - try { - return DbUtil.getFirstObject(rs); - } catch (final SQLException sex) { - throw new DbSqlException(this, "No generated key as long", sex); - } finally { - DbUtil.close(rs); - resultSets.remove(rs); - totalOpenResultSetCount--; - } - } - - - // ---------------------------------------------------------------- query string - - /** - * Returns query SQL string. For prepared statements, returned sql string with quick-and-dirty replaced values. - */ - public String getQueryString() { - if (debug) { - if ((callableStatement != null)) { - if (preparedStatement instanceof LoggableCallableStatement) { - return ((LoggableCallableStatement) callableStatement).getQueryString(); - } - } - if (preparedStatement != null) { - if (preparedStatement instanceof LoggablePreparedStatement) { - return ((LoggablePreparedStatement) preparedStatement).getQueryString(); - } - } - } - if (query != null) { - return query.sql; - } - return sqlString; - } - - /** - * @see #getQueryString() - */ - @Override - public String toString() { - return getQueryString(); - } - - - - // ---------------------------------------------------------------- statistics - - - protected static int totalOpenResultSetCount; - - /** - * Returns total number of open result sets. - * @see #getOpenResultSetCount() - */ - public static int getTotalOpenResultSetCount() { - return totalOpenResultSetCount; - } - - /** - * Returns number of created result sets that are still not explicitly closed. - * @see #getTotalOpenResultSetCount() - */ - public int getOpenResultSetCount() { - return resultSets == null ? 0 : resultSets.size(); - } -} diff --git a/jodd-db/src/main/java/jodd/db/DbQueryConfig.java b/jodd-db/src/main/java/jodd/db/DbQueryConfig.java deleted file mode 100644 index 354d2cc71..000000000 --- a/jodd-db/src/main/java/jodd/db/DbQueryConfig.java +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db; - -/** - * Db query default configuration. - */ -public class DbQueryConfig { - - /** - * Default debug mode. - */ - private boolean debug = false; - /** - * Enables creation of prepared statements for all queries. - */ - private boolean forcePreparedStatement = false; - /** - * Default type. - */ - private QueryScrollType type = QueryScrollType.FORWARD_ONLY; - /** - * Default concurrency type. - */ - private QueryConcurrencyType concurrencyType = QueryConcurrencyType.READ_ONLY; - /** - * Default holdability. - */ - private QueryHoldability holdability = QueryHoldability.DEFAULT; - /** - * Default value for fetch size. - */ - private int fetchSize = 0; - /** - * Default value for max rows. - */ - private int maxRows = 0; - - - public boolean isDebug() { - return debug; - } - - public void setDebug(final boolean debug) { - this.debug = debug; - } - - public boolean isForcePreparedStatement() { - return forcePreparedStatement; - } - - public void setForcePreparedStatement(final boolean forcePreparedStatement) { - this.forcePreparedStatement = forcePreparedStatement; - } - - public QueryScrollType getType() { - return type; - } - - public void setType(final QueryScrollType type) { - this.type = type; - } - - public QueryConcurrencyType getConcurrencyType() { - return concurrencyType; - } - - public void setConcurrencyType(final QueryConcurrencyType concurrencyType) { - this.concurrencyType = concurrencyType; - } - - public QueryHoldability getHoldability() { - return holdability; - } - - public void setHoldability(final QueryHoldability holdability) { - this.holdability = holdability; - } - - public int getFetchSize() { - return fetchSize; - } - - public void setFetchSize(final int fetchSize) { - this.fetchSize = fetchSize; - } - - public int getMaxRows() { - return maxRows; - } - - public void setMaxRows(final int maxRows) { - this.maxRows = maxRows; - } -} diff --git a/jodd-db/src/main/java/jodd/db/DbQueryNamedParameter.java b/jodd-db/src/main/java/jodd/db/DbQueryNamedParameter.java deleted file mode 100644 index 02669d6c4..000000000 --- a/jodd-db/src/main/java/jodd/db/DbQueryNamedParameter.java +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db; - -import java.util.Arrays; - -/** - * Storage for named parameters. - */ -class DbQueryNamedParameter { - /** - * Name. - */ - public final String name; - /** - * Indices. - */ - public int[] indices; - public DbQueryNamedParameter next; - - DbQueryNamedParameter(final String name) { - this.name = name; - } - - public boolean equalsName(final String name) { - return this.name.equals(name); - } - - public void add(final int index) { - indices = Arrays.copyOf(indices, indices.length + 1); - indices[indices.length - 1] = index; - } -} diff --git a/jodd-db/src/main/java/jodd/db/DbQueryParser.java b/jodd-db/src/main/java/jodd/db/DbQueryParser.java deleted file mode 100644 index be3c76e94..000000000 --- a/jodd-db/src/main/java/jodd/db/DbQueryParser.java +++ /dev/null @@ -1,243 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db; - -import jodd.util.CharUtil; -import jodd.util.StringUtil; - -import java.util.HashMap; -import java.util.Map; -import java.util.function.Consumer; - -/** - * SQL parameters parser that recognizes named and ordinal parameters. - */ -class DbQueryParser { - - public static final String SQL_SEPARATORS = " \n\r\f\t,()=<>&|+-=/*'^![]#~\\"; - - boolean prepared; - boolean callable; - String sql; - - // ---------------------------------------------------------------- ctors - - DbQueryParser(final String sql) { - parseSql(sql); - } - - // ---------------------------------------------------------------- parameters - - private DbQueryNamedParameter rootNP; - - void storeNamedParameter(final String name, final int position) { - DbQueryNamedParameter p = lookupNamedParameter(name); - if (p == null) { - p = new DbQueryNamedParameter(name); - p.indices = new int[] {position}; - p.next = rootNP; - rootNP = p; - } - else { - p.add(position); - } - } - - /** - * Lookup for named parameter. - */ - DbQueryNamedParameter lookupNamedParameter(final String name) { - DbQueryNamedParameter p = rootNP; - while (p != null) { - if (p.equalsName(name)) { - return p; - } - p = p.next; - } - return null; - } - - int[] getNamedParameterIndices(final String name) { - final DbQueryNamedParameter p = lookupNamedParameter(name); - if (p == null) { - throw new DbSqlException("Named parameter not found: " + name + "\nQuery: " + sql); - } - return p.indices; - } - - void forEachNamedParameter(final Consumerconsumer) { - DbQueryNamedParameter p = rootNP; - while (p != null) { - consumer.accept(p); - p = p.next; - } - } - - // ---------------------------------------------------------------- batch - - private Map batchParams; - - private void saveBatchParameter(final String name, final int size) { - if (batchParams == null) { - batchParams = new HashMap<>(); - } - batchParams.put(name, Integer.valueOf(size)); - } - - /** - * Returns the size of batch parameter. Returns 0
- * if parameter does not exist. - */ - protected int getBatchParameterSize(final String name) { - if (batchParams == null) { - return 0; - } - Integer size = batchParams.get(name); - if (size == null) { - return 0; - } - return size.intValue(); - } - - // ---------------------------------------------------------------- parser - - void parseSql(final String sqlString) { - rootNP = null; - final int stringLength = sqlString.length(); - final StringBuilder pureSql = new StringBuilder(stringLength); - boolean inQuote = false; - int index = 0; - int paramCount = 0; - - while (index < stringLength) { - char c = sqlString.charAt(index); - if (inQuote) { - if (c == '\'') { - inQuote = false; - } - } - else if (c == '\'') { - inQuote = true; - } - else if (c == ':' && index + 1 < stringLength - && sqlString.charAt(index + 1) == ':') { - // don't treat '::foo' sequence as named parameter; skip this - // chunk - int right = StringUtil.indexOfChars(sqlString, - SQL_SEPARATORS, index + 2); - if (right < 0) { - right = stringLength; - } - pureSql.append(sqlString.substring(index, right)); - index = right; - continue; - } - else if (c == ':') { - int right = StringUtil.indexOfChars(sqlString, SQL_SEPARATORS, index + 1); - boolean batch = false; - - if (right < 0) { - right = stringLength; - } else { - if (sqlString.charAt(right) == '!') { - batch = true; - } - } - - String param = sqlString.substring(index + 1, right); - - if (!batch) { - paramCount++; - storeNamedParameter(param, paramCount); - pureSql.append('?'); - } - else { - // read batch size - right++; - int numStart = right; - - while (right < stringLength) { - if (!CharUtil.isDigit(sqlString.charAt(right))) { - break; - } - right++; - } - - String numberValue = sqlString.substring(numStart, right); - int batchSize; - try { - batchSize = Integer.parseInt(numberValue); - } catch (NumberFormatException nfex) { - throw new DbSqlException("Batch size is not an integer: " + numberValue, nfex); - } - - saveBatchParameter(param, batchSize); - - // create batch parameters - for (int i = 1; i <= batchSize; i++) { - if (i != 1) { - pureSql.append(','); - } - paramCount++; - storeNamedParameter(param + '.' + i, paramCount); - pureSql.append('?'); - } - } - - index = right; - continue; - } - else if (c == '?') { // either an ordinal or positional parameter - if ((index < stringLength - 1) && (Character.isDigit(sqlString.charAt(index + 1)))) { // positional parameter - int right = StringUtil.indexOfChars(sqlString, SQL_SEPARATORS, index + 1); - if (right < 0) { - right = stringLength; - } - String param = sqlString.substring(index + 1, right); - try { - Integer.parseInt(param); - } catch (NumberFormatException nfex) { - throw new DbSqlException("Positional parameter is not an integer: " + param, nfex); - } - paramCount++; - storeNamedParameter(param, paramCount); - pureSql.append('?'); - index = right; - continue; - } - paramCount++; // ordinal param - } - pureSql.append(c); - index++; - } - this.prepared = (paramCount != 0); - this.sql = pureSql.toString(); - - if (this.sql.startsWith("{")) { - this.callable = true; - } - } -} diff --git a/jodd-db/src/main/java/jodd/db/DbSession.java b/jodd-db/src/main/java/jodd/db/DbSession.java deleted file mode 100644 index b1e75758a..000000000 --- a/jodd-db/src/main/java/jodd/db/DbSession.java +++ /dev/null @@ -1,305 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db; - -import jodd.db.connection.ConnectionProvider; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.sql.Connection; -import java.sql.SQLException; -import java.util.HashSet; -import java.util.Set; - -/** - * Encapsulates db connection. Initially works in auto-commit mode. - * May start and work with transactions, after committing/rolling back - * DbSession goes back to auto-commit mode. - *- * All invoked queries are stored within one session and closed implicitly - * on session closing. - *
- * For managed transaction see
DbJtxTransactionManager
from jodd-tx. - */ -public class DbSession implements AutoCloseable { - - private static final Logger log = LoggerFactory.getLogger(DbSession.class); - - // ---------------------------------------------------------------- init & close - - protected final ConnectionProvider connectionProvider; - protected Connection connection; - - /** - * Creates new database session with default transaction mode and in autocommit mode. - */ - public DbSession(ConnectionProvider connectionProvider) { - log.debug("Creating new db session"); - - if (connectionProvider == null) { - connectionProvider = DbOom.get().connectionProvider(); - - if (connectionProvider == null) { - throw new DbSqlException("Connection provider is not available"); - } - } - - this.connectionProvider = connectionProvider; - this.txActive = false; - this.txMode = DbTransactionMode.READ_ONLY_TX; - this.queries = new HashSet<>(); - } - - - /** - * Closes current session and all allocated resources. - * All attached queries are closed. If a transaction is still active, exception occurs. - * Database connection is returned to the {@link ConnectionProvider}. - * Closed session is no longer available for usage. - */ - public void closeSession() { - log.debug("Closing db session"); - - SQLException sqlException = null; - - if (queries != null) { - for (final DbQueryBase query : queries) { - final SQLException sex = query.closeQuery(); - if (sex != null) { - if (sqlException == null) { - sqlException = sex; - } else { - sqlException.setNextException(sex); - } - } - } - } - if (connection != null) { - if (txActive) { - throw new DbSqlException("TX was not closed before closing the session"); - } - connectionProvider.closeConnection(connection); - connection = null; - } - queries = null; - if (sqlException != null) { - throw new DbSqlException("Closing DbSession failed", sqlException); - } - } - - @Override - public void close() { - closeSession(); - } - - /** - * Indicates whether a session is closed. - */ - public boolean isSessionClosed() { - return queries == null; - } - - /** - * Returnstrue
if session is open. - */ - public boolean isSessionOpen() { - return queries != null; - } - - - // ---------------------------------------------------------------- query - - /** - * Bag of all queries attached to this session. Explicitly closed queries - * remains in the set. Ifnull
, session is closed. - * If notnull
, but empty, session is still considered as open. - */ - protected Setqueries; - - /** - * Returns total number of queries assigned to this session. - */ - public int getTotalQueries() { - if (queries == null) { - return 0; - } - return queries.size(); - } - - /** - * Returns current connection. - */ - public Connection getConnection() { - return connection; - } - - - /** - * Attaches a new {@link DbQuery}. May be invoked both inside and outside of transaction. - */ - protected void attachQuery(final DbQueryBase query) { - assertSessionIsOpen(); - openConnectionForQuery(); - queries.add(query); - } - - /** - * Detach used {@link DbQuery}. Usually invoked by {@link jodd.db.DbQuery#close()}. - */ - protected void detachQuery(final DbQueryBase query) { - queries.remove(query); - } - - - /** - * Opens connection in auto-commit mode, if already not opened. - */ - protected void openConnectionForQuery() { - if (connection == null) { - connection = connectionProvider.getConnection(); - txActive = false; // txAction should already be false - try { - connection.setAutoCommit(true); - } catch (final SQLException sex) { - throw new DbSqlException("Failed to open non-TX connection", sex); - } - } - } - - // ---------------------------------------------------------------- transaction - - protected boolean txActive; - - protected DbTransactionMode txMode; - - /** - * Indicate whether a transaction is in progress. - */ - public boolean isTransactionActive() { - return txActive; - } - - - /** - * Opens a transaction. - */ - protected void openTx() { - if (connection == null) { - connection = connectionProvider.getConnection(); - } - txActive = true; - try { - connection.setAutoCommit(false); - if (txMode.getIsolation() != DbTransactionMode.ISOLATION_DEFAULT) { - connection.setTransactionIsolation(txMode.getIsolation()); - } - connection.setReadOnly(txMode.isReadOnly()); - } catch (final SQLException sex) { - throw new DbSqlException("Open TX failed", sex); - } - } - - /** - * Closes current transaction. - */ - protected void closeTx() { - txActive = false; - try { - connection.setAutoCommit(true); - } catch (final SQLException sex) { - throw new DbSqlException("Close TX failed", sex); - } - } - - - /** - * Starts a transaction. - */ - public void beginTransaction(final DbTransactionMode mode) { - log.debug("Beginning transaction"); - - assertTxIsClosed(); - this.txMode = mode; - openTx(); - } - - /** - * Commit the current transaction, writing any unflushed changes to the database. - * Transaction mode is closed. - */ - public void commitTransaction() { - log.debug("Committing transaction"); - - assertTxIsActive(); - try { - connection.commit(); - } catch (final SQLException sex) { - throw new DbSqlException("Commit TX failed", sex); - } finally { - closeTx(); - } - } - - /** - * Roll back the current transaction. Transaction mode is closed. - */ - public void rollbackTransaction() { - log.debug("Rolling-back transaction"); - - assertTxIsActive(); - - try { - connection.rollback(); - } catch (final SQLException sex) { - throw new DbSqlException("Rollback TX failed", sex); - } finally { - closeTx(); - } - } - - - // ---------------------------------------------------------------- checking - - protected void assertSessionIsOpen() { - if (queries == null) { - throw new DbSqlException("Session is closed"); - } - } - - protected void assertTxIsClosed() { - assertSessionIsOpen(); - if (txActive) { - throw new DbSqlException("TX already started for this session"); - } - } - - protected void assertTxIsActive() { - assertSessionIsOpen(); - if (!txActive) { - throw new DbSqlException("TX not available for this session"); - } - } -} diff --git a/jodd-db/src/main/java/jodd/db/DbSessionProvider.java b/jodd-db/src/main/java/jodd/db/DbSessionProvider.java deleted file mode 100644 index f85eaa11d..000000000 --- a/jodd-db/src/main/java/jodd/db/DbSessionProvider.java +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db; - -/** - * Provide {@link DbSession} when requested by {@link DbQuery}. - * Important: DbSessionProvider
implementations - * should NOT create new db sessions!DbSession
should - * be already created and somehow assigned toDbSessionProvider
- * implementation. User must control session opening and closing, - * and notDbSessionProvider
, as we can not figure - * weather connection should be closed after closing a query; - * or still hold on open for the next query. - */ -@FunctionalInterface -public interface DbSessionProvider { - - /** - * Returns {@link DbSession}. May throws an exception - * if session can not be provided. - */ - DbSession getDbSession(); - -} diff --git a/jodd-db/src/main/java/jodd/db/DbSqlException.java b/jodd-db/src/main/java/jodd/db/DbSqlException.java deleted file mode 100644 index ea5425cfd..000000000 --- a/jodd-db/src/main/java/jodd/db/DbSqlException.java +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db; - -import jodd.exception.UncheckedException; - -/** - * Unchecked SQL exception. - */ -public class DbSqlException extends UncheckedException { - - public DbSqlException(final Throwable t) { - super(t); - } - - public DbSqlException(final String message) { - super(message); - } - - public DbSqlException(final DbQueryBase dbQuery, final String message) { - super(message + "\nQuery: " + dbQuery.getQueryString()); - } - - public DbSqlException(final String message, final Throwable t) { - super(message, t); - } - - public DbSqlException(final DbQueryBase dbQuery, final String message, final Throwable t) { - super(message + "\nQuery: " + dbQuery.getQueryString(), t); - } - -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/DbThreadSession.java b/jodd-db/src/main/java/jodd/db/DbThreadSession.java deleted file mode 100644 index 8f52b5bfe..000000000 --- a/jodd-db/src/main/java/jodd/db/DbThreadSession.java +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db; - -import jodd.db.connection.ConnectionProvider; - -/** - * Thread assigned {@link jodd.db.DbSession}. Upon creation, it assigns - * the session to current thread. Useful when only one session (i.e. connection) - * is used per thread, through service layers. - *- * {@link jodd.db.DbThreadSession} uses {@link jodd.db.ThreadDbSessionHolder} for storing - * created sessions in the thread storage. Note that holder may be manipulated from outside - * of this class. - */ -public class DbThreadSession extends DbSession { - - /** - * Creates new db session and assigns it to the current thread. - * Closes already assigned session, if any exist. - * @param connectionProvider connection provider - */ - public DbThreadSession(final ConnectionProvider connectionProvider) { - super(connectionProvider); - - final DbSession session = ThreadDbSessionHolder.get(); - if (session != null) { - session.closeSession(); - } - ThreadDbSessionHolder.set(this); - } - - /** - * Creates new db session and assigns it to the current thread, using - * default connection provider. - */ - public DbThreadSession() { - this(null); - } - - - /** - * Closes current session and remove the association from current thread. - * @see jodd.db.DbSession#closeSession() - */ - @Override - public void closeSession() { - ThreadDbSessionHolder.remove(); - super.closeSession(); - } - - // ---------------------------------------------------------------- static stuff - - /** - * Returns current thread session or
null
if no session is assigned - * to a thread. - */ - public static DbSession getCurrentSession() { - return ThreadDbSessionHolder.get(); - } - - /** - * Returns existing thread session, or new one if already not exist. If session doesn't exist, it will be created - * using default connection provider. - */ - public static DbThreadSession getThreadSession() { - DbThreadSession session = (DbThreadSession) ThreadDbSessionHolder.get(); - if (session == null) { - session = new DbThreadSession(); - } - return session; - } - - /** - * Closes thread session. - */ - public static void closeThreadSession() { - DbThreadSession session = (DbThreadSession) ThreadDbSessionHolder.get(); - if (session != null) { - session.closeSession(); - } - } - -} diff --git a/jodd-db/src/main/java/jodd/db/DbTransactionMode.java b/jodd-db/src/main/java/jodd/db/DbTransactionMode.java deleted file mode 100644 index b034563d2..000000000 --- a/jodd-db/src/main/java/jodd/db/DbTransactionMode.java +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db; - -import java.sql.Connection; -import java.util.Objects; - -/** - * Native SQL transaction mode for {@link DbSession} transactions. - */ -public class DbTransactionMode { - - // ---------------------------------------------------------------- isolation - - /** - * Default isolation. - */ - public static final int ISOLATION_DEFAULT = -1; - /** - * @see Connection#TRANSACTION_NONE - */ - public static final int ISOLATION_NONE = Connection.TRANSACTION_NONE; - /** - * @see Connection#TRANSACTION_READ_UNCOMMITTED - */ - public static final int ISOLATION_READ_UNCOMMITTED = Connection.TRANSACTION_READ_UNCOMMITTED; - /** - * @see Connection#TRANSACTION_READ_COMMITTED - */ - public static final int ISOLATION_READ_COMMITTED = Connection.TRANSACTION_READ_COMMITTED; - /** - * @see Connection#TRANSACTION_REPEATABLE_READ - */ - public static final int ISOLATION_REPEATABLE_READ = Connection.TRANSACTION_REPEATABLE_READ; - /** - * @see Connection#TRANSACTION_SERIALIZABLE - */ - public static final int ISOLATION_SERIALIZABLE = Connection.TRANSACTION_SERIALIZABLE; - - private final int isolation; - - /** - * Returns isolation level. - */ - public int getIsolation() { - return isolation; - } - - // ---------------------------------------------------------------- read-only - - public static final boolean READ_ONLY = true; - public static final boolean READ_WRITE = false; - - private final boolean readOnlyMode; - - /** - * Returns {@code true} if transaction is read-only. - */ - public boolean isReadOnly() { - return readOnlyMode; - } - - - // ---------------------------------------------------------------- ctor - - public static final DbTransactionMode READ_ONLY_TX = new DbTransactionMode(ISOLATION_DEFAULT, READ_ONLY); - public static final DbTransactionMode READ_WRITE_TX = new DbTransactionMode(ISOLATION_DEFAULT, READ_WRITE); - - public DbTransactionMode(final int isolation, boolean readOnlyMode) { - this.isolation = isolation; - this.readOnlyMode = readOnlyMode; - } - - // ---------------------------------------------------------------- equals & hashCode - - @Override - public boolean equals(final Object object) { - if (this == object) { - return true; - } - if (this.getClass() != object.getClass()) { - return false; - } - DbTransactionMode mode = (DbTransactionMode) object; - return (mode.getIsolation() == this.isolation) && - (mode.isReadOnly() == this.readOnlyMode); - } - - @Override - public int hashCode() { - return Objects.hash(readOnlyMode, isolation); - } - - -} diff --git a/jodd-db/src/main/java/jodd/db/DbUtil.java b/jodd-db/src/main/java/jodd/db/DbUtil.java deleted file mode 100644 index e310c67b2..000000000 --- a/jodd-db/src/main/java/jodd/db/DbUtil.java +++ /dev/null @@ -1,174 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db; - -import jodd.db.type.SqlType; -import jodd.typeconverter.Converter; -import jodd.typeconverter.TypeConverterManager; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.sql.Timestamp; -import java.sql.Types; - -/** - * Various DB utilities. - */ -public class DbUtil { - - /** - * Closes statement safely without throwing an exception. - */ - public static void close(final Statement statement) { - if (statement == null) { - return; - } - - try { - statement.close(); - } catch (SQLException sex) { - // ignore - } - } - - /** - * Closes result set safely without throwing an exception. - */ - public static void close(final ResultSet resultSet) { - if (resultSet == null) { - return; - } - try { - resultSet.close(); - } catch (SQLException sex) { - // ignore - } - } - - /** - * Returns long value of very first column in result set. - */ - public static long getFirstLong(final ResultSet resultSet) throws SQLException { - if (resultSet.next()) { - return resultSet.getLong(1); - } - return -1; - } - - /** - * Returns int value of very first column in result set. - */ - public static int getFirstInt(final ResultSet resultSet) throws SQLException { - if (resultSet.next()) { - return resultSet.getInt(1); - } - return -1; - } - - public static Object getFirstObject(final ResultSet resultSet) throws SQLException { - if (resultSet.next()) { - return resultSet.getObject(1); - } - return null; - } - - /** - * Sets prepared statement object using target SQL type. - * Here Jodd makes conversion and not JDBC driver. - * See: http://www.tutorialspoint.com/jdbc/jdbc-data-types.htm - */ - public static void setPreparedStatementObject(final PreparedStatement preparedStatement, final int index, final Object value, final int targetSqlType) throws SQLException { - if (value == null) { - preparedStatement.setNull(index, Types.NULL); - return; - } - - switch (targetSqlType) { - case Types.VARCHAR: - case Types.LONGVARCHAR: - case Types.CHAR: - preparedStatement.setString(index, Converter.get().toString(value)); - break; - - case Types.INTEGER: - case Types.SMALLINT: - case Types.TINYINT: - preparedStatement.setInt(index, Converter.get().toIntValue(value)); - break; - - case Types.BIGINT: - preparedStatement.setLong(index, Converter.get().toLongValue(value)); - break; - - case Types.BOOLEAN: - case Types.BIT: - preparedStatement.setBoolean(index, Converter.get().toBooleanValue(value)); - break; - - case Types.DATE: - preparedStatement.setDate(index, TypeConverterManager.get().convertType(value, java.sql.Date.class)); - break; - - case Types.NUMERIC: - case Types.DECIMAL: - preparedStatement.setBigDecimal(index, Converter.get().toBigDecimal(value)); - break; - - case Types.DOUBLE: - preparedStatement.setDouble(index, Converter.get().toDoubleValue(value)); - break; - - case Types.REAL: - case Types.FLOAT: - preparedStatement.setFloat(index, Converter.get().toFloatValue(value)); - break; - - case Types.TIME: - preparedStatement.setTime(index, TypeConverterManager.get().convertType(value, java.sql.Time.class)); - break; - - case Types.TIMESTAMP: - preparedStatement.setTimestamp(index, TypeConverterManager.get().convertType(value, Timestamp.class)); - break; - - case Types.BINARY: - case Types.VARBINARY: - preparedStatement.setBytes(index, TypeConverterManager.get().convertType(value, byte[].class)); - break; - - default: - if (targetSqlType != SqlType.DB_SQLTYPE_NOT_AVAILABLE) { - preparedStatement.setObject(index, value, targetSqlType); - } else { - preparedStatement.setObject(index, value); - } - } - - } - -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/QueryConcurrencyType.java b/jodd-db/src/main/java/jodd/db/QueryConcurrencyType.java deleted file mode 100644 index 75740914d..000000000 --- a/jodd-db/src/main/java/jodd/db/QueryConcurrencyType.java +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db; - -import java.sql.ResultSet; - -/** - * Query concurrency type. - */ -public enum QueryConcurrencyType { - - READ_ONLY(ResultSet.CONCUR_READ_ONLY), - UPDATABLE(ResultSet.CONCUR_UPDATABLE); - - private final int type; - - QueryConcurrencyType(final int type) { - this.type = type; - } - - public int value() { - return type; - } - -} diff --git a/jodd-db/src/main/java/jodd/db/QueryHoldability.java b/jodd-db/src/main/java/jodd/db/QueryHoldability.java deleted file mode 100644 index cbffd6eb2..000000000 --- a/jodd-db/src/main/java/jodd/db/QueryHoldability.java +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db; - -import java.sql.ResultSet; - -/** - * Query holdability. - */ -public enum QueryHoldability { - /** - * Default holdability. JDBC specification does not specifies default value for holdability. - */ - DEFAULT(-1), - CLOSE_CURSORS_AT_COMMIT(ResultSet.CLOSE_CURSORS_AT_COMMIT), - HOLD_CURSORS_OVER_COMMIT(ResultSet.HOLD_CURSORS_OVER_COMMIT); - - private final int type; - - QueryHoldability(final int type) { - this.type = type; - } - - public int value() { - return type; - } - -} diff --git a/jodd-db/src/main/java/jodd/db/QueryMapper.java b/jodd-db/src/main/java/jodd/db/QueryMapper.java deleted file mode 100644 index f71497725..000000000 --- a/jodd-db/src/main/java/jodd/db/QueryMapper.java +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db; - -import java.sql.ResultSet; -import java.sql.SQLException; - -/** - * Process {@link jodd.db.DbQuery query} and map it execution result to a type. - */ -public interface QueryMapper{ - - /** - * Processes single result sets row. - * Returns null
to stop iterations. - */ - T process(ResultSet resultSet) throws SQLException; - -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/QueryScrollType.java b/jodd-db/src/main/java/jodd/db/QueryScrollType.java deleted file mode 100644 index 94663e66e..000000000 --- a/jodd-db/src/main/java/jodd/db/QueryScrollType.java +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db; - -import java.sql.ResultSet; - -/** - * Query scroll type. - */ -public enum QueryScrollType { - /** - * @see ResultSet#TYPE_FORWARD_ONLY - */ - FORWARD_ONLY(ResultSet.TYPE_FORWARD_ONLY), - /** - * @see ResultSet#TYPE_SCROLL_SENSITIVE - */ - SCROLL_SENSITIVE(ResultSet.TYPE_SCROLL_SENSITIVE), - /** - * @see ResultSet#TYPE_SCROLL_INSENSITIVE - */ - SCROLL_INSENSITIVE(ResultSet.TYPE_SCROLL_INSENSITIVE); - - private final int type; - - QueryScrollType(final int type) { - this.type = type; - } - - public int value() { - return type; - } - -} diff --git a/jodd-db/src/main/java/jodd/db/ThreadDbSessionHolder.java b/jodd-db/src/main/java/jodd/db/ThreadDbSessionHolder.java deleted file mode 100644 index 634828434..000000000 --- a/jodd-db/src/main/java/jodd/db/ThreadDbSessionHolder.java +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db; - -/** - * {@link DbSession} thread storage. - */ -public class ThreadDbSessionHolder { - - private static final ThreadLocalDB_SESSION_THREAD_LOCAL = new ThreadLocal<>(); - - /** - * Returns current thread db session. - */ - public static DbSession get() { - return DB_SESSION_THREAD_LOCAL.get(); - } - - /** - * Sets current db session. - */ - public static void set(final DbSession dbSession) { - DB_SESSION_THREAD_LOCAL.set(dbSession); - } - - /** - * Removes current db session from the thread and returns it. - */ - public static void remove() { - DB_SESSION_THREAD_LOCAL.set(null); - } -} diff --git a/jodd-db/src/main/java/jodd/db/ThreadDbSessionProvider.java b/jodd-db/src/main/java/jodd/db/ThreadDbSessionProvider.java deleted file mode 100644 index 52e358df1..000000000 --- a/jodd-db/src/main/java/jodd/db/ThreadDbSessionProvider.java +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Returns {@link DbSession} assigned to current thread. - * @see DbThreadSession - * @see ThreadDbSessionHolder - */ -public class ThreadDbSessionProvider implements DbSessionProvider { - - private static final Logger log = LoggerFactory.getLogger(ThreadDbSessionProvider.class); - - /** - * {@inheritDoc} - */ - @Override - public DbSession getDbSession() { - log.debug("Requesting thread session"); - - final DbSession session = ThreadDbSessionHolder.get(); - - if (session == null) { - throw new DbSqlException( - "No DbSession associated with current thread. " + - "It seems that ThreadDbSessionHolder is not used."); - } - return session; - } - - -} diff --git a/jodd-db/src/main/java/jodd/db/connection/ConnectionPoolDataSourceConnectionProvider.java b/jodd-db/src/main/java/jodd/db/connection/ConnectionPoolDataSourceConnectionProvider.java deleted file mode 100644 index 6909e10ae..000000000 --- a/jodd-db/src/main/java/jodd/db/connection/ConnectionPoolDataSourceConnectionProvider.java +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.connection; - -import jodd.db.DbSqlException; - -import javax.sql.ConnectionPoolDataSource; -import javax.sql.PooledConnection; -import java.sql.Connection; -import java.sql.SQLException; - -/** - * Connection pool data source {@link jodd.db.connection.ConnectionProvider} - */ -public class ConnectionPoolDataSourceConnectionProvider implements ConnectionProvider { - // ---------------------------------------------------------------- properties - - private ConnectionPoolDataSource cpds; - - public ConnectionPoolDataSourceConnectionProvider(final ConnectionPoolDataSource cpds) { - this.cpds = cpds; - } - - // ---------------------------------------------------------------- init/close - - @Override - public void init() { - } - - @Override - public void close() { - cpds = null; - } - - // ---------------------------------------------------------------- get/free - - @Override - public Connection getConnection() { - PooledConnection pconn; - try { - pconn = cpds.getPooledConnection(); - } catch (SQLException sex) { - throw new DbSqlException("Invalid pooled connection", sex); - } - try { - return pconn.getConnection(); - } catch (SQLException sex) { - throw new DbSqlException("Invalid pooled connection", sex); - } - } - - @Override - public void closeConnection(final Connection connection) { - try { - if (connection != null) { - connection.close(); - } - } catch (SQLException sex) { - // ignore - } - } -} diff --git a/jodd-db/src/main/java/jodd/db/connection/ConnectionProvider.java b/jodd-db/src/main/java/jodd/db/connection/ConnectionProvider.java deleted file mode 100644 index 92402175c..000000000 --- a/jodd-db/src/main/java/jodd/db/connection/ConnectionProvider.java +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.connection; - -import java.sql.Connection; - -/** - * A generic strategy for obtaining JDBC connections. - * - * Implementors might also implement connection pooling. - *
- * Implementations should provide a public default constructor. - */ -public interface ConnectionProvider extends AutoCloseable { - - /** - * Initialize the connection provider. May be called more then once; - * does not have any effect if pool is already initialized. - */ - void init(); - - /** - * Returns a connection from connection pool. - */ - Connection getConnection(); - - /** - * Dispose of a used {@link #getConnection() connection}. - */ - void closeConnection(Connection connection); - - /** - * Closes a provider and releases all its resources. - */ - @Override - void close(); - -} diff --git a/jodd-db/src/main/java/jodd/db/connection/DataSourceConnectionProvider.java b/jodd-db/src/main/java/jodd/db/connection/DataSourceConnectionProvider.java deleted file mode 100644 index e885f8f6d..000000000 --- a/jodd-db/src/main/java/jodd/db/connection/DataSourceConnectionProvider.java +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.connection; - -import jodd.db.DbSqlException; - -import javax.naming.InitialContext; -import javax.naming.NamingException; -import javax.sql.DataSource; -import java.sql.Connection; -import java.sql.SQLException; - -/** - * DataSource connection provider. Note that data source implementation might - * not support
dataSource.getConnection(username, password)
. - */ -public class DataSourceConnectionProvider implements ConnectionProvider { - - private final DataSource dataSource; - private final String username; - private final String password; - - public DataSourceConnectionProvider(final String jndiName) { - this(jndiName, null, null); - } - - public DataSourceConnectionProvider(final String jndiName, final String user, final String pass) { - try { - InitialContext initialContext = new InitialContext(); - - this.dataSource = (DataSource) initialContext.lookup(jndiName); - } catch (NamingException nex) { - throw new DbSqlException("Invalid JNDI datasource name: " + jndiName, nex); - } - this.username = user; - this.password = pass; - } - - public DataSourceConnectionProvider(final DataSource dataSource) { - this.dataSource = dataSource; - username = password = null; - } - - public DataSourceConnectionProvider(final DataSource dataSource, final String user, final String pass) { - this.dataSource = dataSource; - this.username = user; - this.password = pass; - } - - @Override - public void init() {} - - @Override - public Connection getConnection() { - try { - if (username != null || password != null) { - return dataSource.getConnection(username, password); - } else { - return dataSource.getConnection(); - } - } catch (SQLException sex) { - throw new DbSqlException("Invalid datasource connection", sex); - } - } - - @Override - public void closeConnection(final Connection connection) { - try { - connection.close(); - } catch (SQLException sex) { - // ignore - } - } - - @Override - public void close() {} -} diff --git a/jodd-db/src/main/java/jodd/db/connection/DriverManagerConnectionProvider.java b/jodd-db/src/main/java/jodd/db/connection/DriverManagerConnectionProvider.java deleted file mode 100644 index 9a3c5329c..000000000 --- a/jodd-db/src/main/java/jodd/db/connection/DriverManagerConnectionProvider.java +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.connection; - -import jodd.db.DbSqlException; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -/** - * Driver manager connection provider; - */ -public class DriverManagerConnectionProvider implements ConnectionProvider { - - // ---------------------------------------------------------------- properties - - private String url; - private String username; - private String password; - private String driverClass; - private Integer isolation; - private Boolean autoCommit; - - public void setUrl(final String url) { - this.url = url; - } - - public void setUsername(final String username) { - this.username = username; - } - - public void setPassword(final String password) { - this.password = password; - } - - public void setDriverClass(final String driverClass) { - this.driverClass = driverClass; - } - - public void setIsolation(final Integer isolation) { - this.isolation = isolation; - } - - public void setAutoCommit(final Boolean autoCommit) { - this.autoCommit = autoCommit; - } - - // ---------------------------------------------------------------- ctors - - public DriverManagerConnectionProvider(final String driverClass, final String url, final String username, final String password) { - this.driverClass = driverClass; - this.password = password; - this.username = username; - this.url = url; - } - public DriverManagerConnectionProvider(final String driverClass, final String url) { - this.driverClass = driverClass; - this.url = url; - } - - // ---------------------------------------------------------------- provider - - @Override - public synchronized void init() { - try { - Class.forName(driverClass); - } catch (ClassNotFoundException cnfex) { - throw new DbSqlException("JDBC driver not found: " + driverClass, cnfex); - } - } - - @Override - public Connection getConnection() { - Connection conn; - try { - if (username != null) { - conn = DriverManager.getConnection(url, username, password); - } else { - conn = DriverManager.getConnection(url); - } - if (isolation != null) { - conn.setTransactionIsolation(isolation.intValue()); - } - if (autoCommit != null) { - conn.setAutoCommit(autoCommit.booleanValue()); - } - } - catch (SQLException sex) { - throw new DbSqlException("Connection not found", sex); - } - return conn; - } - - @Override - public void closeConnection(final Connection connection) { - try { - connection.close(); - } catch (SQLException sex) { - // ignore - } - } - - @Override - public void close() { - } -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/connection/XADataSourceConnectionProvider.java b/jodd-db/src/main/java/jodd/db/connection/XADataSourceConnectionProvider.java deleted file mode 100644 index ac55a58be..000000000 --- a/jodd-db/src/main/java/jodd/db/connection/XADataSourceConnectionProvider.java +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.connection; - -import jodd.db.DbSqlException; - -import javax.sql.XAConnection; -import javax.sql.XADataSource; -import java.sql.Connection; -import java.sql.SQLException; - -/** - * XA-DataSource connection provider. - */ -public class XADataSourceConnectionProvider implements ConnectionProvider { - - private final XADataSource xaDataSource; - private final String username; - private final String password; - - public XADataSourceConnectionProvider(final XADataSource dataSource) { - this.xaDataSource = dataSource; - this.username = this.password = null; - } - public XADataSourceConnectionProvider(final XADataSource dataSource, final String user, final String pass) { - this.xaDataSource = dataSource; - this.username = user; - this.password = pass; - } - - @Override - public void init() {} - - @Override - public Connection getConnection() { - try { - XAConnection xaConnection; - if (username != null) { - xaConnection = xaDataSource.getXAConnection(username, password); - } else { - xaConnection = xaDataSource.getXAConnection(); - } - return xaConnection.getConnection(); - } catch (SQLException sex) { - throw new DbSqlException("Unable to get connection from XA datasource", sex); - } - } - - @Override - public void closeConnection(final Connection connection) { - try { - connection.close(); - } catch (SQLException sex) { - // ignore - } - } - - @Override - public void close() {} -} diff --git a/jodd-db/src/main/java/jodd/db/connection/package-info.java b/jodd-db/src/main/java/jodd/db/connection/package-info.java deleted file mode 100644 index 3f7607524..000000000 --- a/jodd-db/src/main/java/jodd/db/connection/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Various database connection providers. - */ -package jodd.db.connection; \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/debug/BaseLoggableStatement.java b/jodd-db/src/main/java/jodd/db/debug/BaseLoggableStatement.java deleted file mode 100644 index e407f7846..000000000 --- a/jodd-db/src/main/java/jodd/db/debug/BaseLoggableStatement.java +++ /dev/null @@ -1,348 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.debug; - -import jodd.typeconverter.Converter; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.SQLWarning; -import java.sql.Statement; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; -import java.util.ArrayList; -import java.util.Date; -import java.util.StringTokenizer; - -public abstract class BaseLoggableStatementimplements Statement { - - protected final S wrappedStatement; - protected final String sqlTemplate; - - public BaseLoggableStatement(final S wrappedStatement, final String sqlTemplate) { - this.wrappedStatement = wrappedStatement; - this.sqlTemplate = sqlTemplate; - } - - // ---------------------------------------------------------------- query - - protected ArrayListparameterValues; - - /** - * Returns the query string. - */ - public String getQueryString() { - if (sqlTemplate == null) { - return toString(); - } - if (parameterValues == null) { - return sqlTemplate; - } - - final StringBuilder sb = new StringBuilder(); - - int qMarkCount = 0; - final StringTokenizer tok = new StringTokenizer(sqlTemplate + ' ', "?"); - - while (tok.hasMoreTokens()) { - final String oneChunk = tok.nextToken(); - sb.append(oneChunk); - try { - Object value = null; - if (parameterValues.size() > 1 + qMarkCount) { - value = parameterValues.get(1 + qMarkCount); - qMarkCount++; - } else { - if (!tok.hasMoreTokens()) { - value = ""; - } - } - if (value == null) { - value = "?"; - } - sb.append(value); - } catch (Throwable th) { - sb.append("--- Building query failed: ").append(th.toString()); - } - } - return sb.toString().trim(); - } - - /** - * Saves the parameter value obj
for the specified - *position
for use in logging output. - * - * @param position position (starting at 1) of the parameter to save - * @param obj java.lang.Object the parameter value to save - */ - protected void saveQueryParamValue(final int position, final Object obj) { - final String strValue; - if (obj instanceof String || obj instanceof Date) { - strValue = "'" + obj + '\''; // if we have a String or Date, include '' in the saved value - } else if (obj instanceof LocalDateTime || obj instanceof LocalDate || obj instanceof LocalTime) { - strValue = "'" + Converter.get().toString(obj) + '\''; // time as string with ' - } else if (obj == null) { - strValue = ""; // convert null to the string null - } else { - strValue = Converter.get().toString(obj); // all other objects (includes all Numbers, arrays, etc) - } - - // if we are setting a position larger than current size of parameterValues, - // first make it larger - if (parameterValues == null) { - parameterValues = new ArrayList<>(); - } - - while (position >= parameterValues.size()) { - parameterValues.add(null); - } - parameterValues.set(position, strValue); - } - - // ---------------------------------------------------------------- statement - - @Override - public ResultSet executeQuery(String sql) throws SQLException { - return wrappedStatement.executeQuery(sql); - } - - @Override - public int executeUpdate(String sql) throws SQLException { - return wrappedStatement.executeUpdate(sql); - } - - @Override - public void close() throws SQLException { - wrappedStatement.close(); - } - - @Override - public int getMaxFieldSize() throws SQLException { - return wrappedStatement.getMaxFieldSize(); - } - - @Override - public void setMaxFieldSize(int max) throws SQLException { - wrappedStatement.setMaxFieldSize(max); - } - - @Override - public int getMaxRows() throws SQLException { - return wrappedStatement.getMaxRows(); - } - - @Override - public void setMaxRows(int max) throws SQLException { - wrappedStatement.setMaxRows(max); - } - - @Override - public void setEscapeProcessing(boolean enable) throws SQLException { - wrappedStatement.setEscapeProcessing(enable); - } - - @Override - public int getQueryTimeout() throws SQLException { - return wrappedStatement.getQueryTimeout(); - } - - @Override - public void setQueryTimeout(int seconds) throws SQLException { - wrappedStatement.setQueryTimeout(seconds); - } - - @Override - public void cancel() throws SQLException { - wrappedStatement.cancel(); - } - - @Override - public SQLWarning getWarnings() throws SQLException { - return wrappedStatement.getWarnings(); - } - - @Override - public void clearWarnings() throws SQLException { - wrappedStatement.clearWarnings(); - } - - @Override - public void setCursorName(String name) throws SQLException { - wrappedStatement.setCursorName(name); - } - - @Override - public boolean execute(String sql) throws SQLException { - return wrappedStatement.execute(sql); - } - - @Override - public ResultSet getResultSet() throws SQLException { - return wrappedStatement.getResultSet(); - } - - @Override - public int getUpdateCount() throws SQLException { - return wrappedStatement.getUpdateCount(); - } - - @Override - public boolean getMoreResults() throws SQLException { - return wrappedStatement.getMoreResults(); - } - - @Override - public void setFetchDirection(int direction) throws SQLException { - wrappedStatement.setFetchDirection(direction); - } - - @Override - public int getFetchDirection() throws SQLException { - return wrappedStatement.getFetchDirection(); - } - - @Override - public void setFetchSize(int rows) throws SQLException { - wrappedStatement.setFetchDirection(rows); - } - - @Override - public int getFetchSize() throws SQLException { - return wrappedStatement.getFetchSize(); - } - - @Override - public int getResultSetConcurrency() throws SQLException { - return wrappedStatement.getResultSetConcurrency(); - } - - @Override - public int getResultSetType() throws SQLException { - return wrappedStatement.getResultSetType(); - } - - @Override - public void addBatch(String sql) throws SQLException { - wrappedStatement.addBatch(sql); - } - - @Override - public void clearBatch() throws SQLException { - wrappedStatement.clearBatch(); - } - - @Override - public int[] executeBatch() throws SQLException { - return wrappedStatement.executeBatch(); - } - - @Override - public Connection getConnection() throws SQLException { - return wrappedStatement.getConnection(); - } - - @Override - public boolean getMoreResults(int current) throws SQLException { - return wrappedStatement.getMoreResults(current); - } - - @Override - public ResultSet getGeneratedKeys() throws SQLException { - return wrappedStatement.getGeneratedKeys(); - } - - @Override - public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException { - return wrappedStatement.executeUpdate(sql, autoGeneratedKeys); - } - - @Override - public int executeUpdate(String sql, int[] columnIndexes) throws SQLException { - return wrappedStatement.executeUpdate(sql, columnIndexes); - } - - @Override - public int executeUpdate(String sql, String[] columnNames) throws SQLException { - return wrappedStatement.executeUpdate(sql, columnNames); - } - - @Override - public boolean execute(String sql, int autoGeneratedKeys) throws SQLException { - return wrappedStatement.execute(sql, autoGeneratedKeys); - } - - @Override - public boolean execute(String sql, int[] columnIndexes) throws SQLException { - return wrappedStatement.execute(sql, columnIndexes); - } - - @Override - public boolean execute(String sql, String[] columnNames) throws SQLException { - return wrappedStatement.execute(sql, columnNames); - } - - @Override - public int getResultSetHoldability() throws SQLException { - return wrappedStatement.getResultSetHoldability(); - } - - @Override - public boolean isClosed() throws SQLException { - return wrappedStatement.isClosed(); - } - - @Override - public void setPoolable(boolean poolable) throws SQLException { - wrappedStatement.setPoolable(poolable); - } - - @Override - public boolean isPoolable() throws SQLException { - return wrappedStatement.isPoolable(); - } - - @Override - public void closeOnCompletion() throws SQLException { - wrappedStatement.closeOnCompletion(); - } - - @Override - public boolean isCloseOnCompletion() throws SQLException { - return wrappedStatement.isCloseOnCompletion(); - } - - @Override - public T unwrap(Class iface) throws SQLException { - return wrappedStatement.unwrap(iface); - } - - @Override - public boolean isWrapperFor(Class> iface) throws SQLException { - return wrappedStatement.isWrapperFor(iface); - } -} diff --git a/jodd-db/src/main/java/jodd/db/debug/LoggableCallableStatement.java b/jodd-db/src/main/java/jodd/db/debug/LoggableCallableStatement.java deleted file mode 100644 index d00fba877..000000000 --- a/jodd-db/src/main/java/jodd/db/debug/LoggableCallableStatement.java +++ /dev/null @@ -1,622 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.debug; - -import java.io.InputStream; -import java.io.Reader; -import java.math.BigDecimal; -import java.net.URL; -import java.sql.Array; -import java.sql.Blob; -import java.sql.CallableStatement; -import java.sql.Clob; -import java.sql.Date; -import java.sql.NClob; -import java.sql.Ref; -import java.sql.RowId; -import java.sql.SQLException; -import java.sql.SQLXML; -import java.sql.Time; -import java.sql.Timestamp; -import java.util.Calendar; -import java.util.Map; - -public class LoggableCallableStatement extends LoggablePreparedStatement implements CallableStatement { - private CallableStatement callableStatement; - - public LoggableCallableStatement(final CallableStatement wrappedStatement, final String sqlTemplate) { - super(wrappedStatement, sqlTemplate); - this.callableStatement = wrappedStatement; - } - - @Override - public void registerOutParameter(int parameterIndex, int sqlType) throws SQLException { - callableStatement.registerOutParameter(parameterIndex, sqlType); - } - - @Override - public void registerOutParameter(int parameterIndex, int sqlType, int scale) throws SQLException { - callableStatement.registerOutParameter(parameterIndex, sqlType, scale); - } - - @Override - public boolean wasNull() throws SQLException { - return callableStatement.wasNull(); - } - - @Override - public String getString(int parameterIndex) throws SQLException { - return callableStatement.getString(parameterIndex); - } - - @Override - public boolean getBoolean(int parameterIndex) throws SQLException { - return callableStatement.getBoolean(parameterIndex); - } - - @Override - public byte getByte(int parameterIndex) throws SQLException { - return callableStatement.getByte(parameterIndex); - } - - @Override - public short getShort(int parameterIndex) throws SQLException { - return callableStatement.getShort(parameterIndex); - } - - @Override - public int getInt(int parameterIndex) throws SQLException { - return callableStatement.getInt(parameterIndex); - } - - @Override - public long getLong(int parameterIndex) throws SQLException { - return callableStatement.getLong(parameterIndex); - } - - @Override - public float getFloat(int parameterIndex) throws SQLException { - return callableStatement.getFloat(parameterIndex); - } - - @Override - public double getDouble(int parameterIndex) throws SQLException { - return callableStatement.getDouble(parameterIndex); - } - - @Override - @Deprecated - public BigDecimal getBigDecimal(int parameterIndex, int scale) throws SQLException { - return callableStatement.getBigDecimal(parameterIndex, scale); - } - - @Override - public byte[] getBytes(int parameterIndex) throws SQLException { - return callableStatement.getBytes(parameterIndex); - } - - @Override - public Date getDate(int parameterIndex) throws SQLException { - return callableStatement.getDate(parameterIndex); - } - - @Override - public Time getTime(int parameterIndex) throws SQLException { - return callableStatement.getTime(parameterIndex); - } - - @Override - public Timestamp getTimestamp(int parameterIndex) throws SQLException { - return callableStatement.getTimestamp(parameterIndex); - } - - @Override - public Object getObject(int parameterIndex) throws SQLException { - return callableStatement.getObject(parameterIndex); - } - - @Override - public BigDecimal getBigDecimal(int parameterIndex) throws SQLException { - return callableStatement.getBigDecimal(parameterIndex); - } - - @Override - public Object getObject(int parameterIndex, Map > map) throws SQLException { - return callableStatement.getObject(parameterIndex, map); - } - - @Override - public Ref getRef(int parameterIndex) throws SQLException { - return callableStatement.getRef(parameterIndex); - } - - @Override - public Blob getBlob(int parameterIndex) throws SQLException { - return callableStatement.getBlob(parameterIndex); - } - - @Override - public Clob getClob(int parameterIndex) throws SQLException { - return callableStatement.getClob(parameterIndex); - } - - @Override - public Array getArray(int parameterIndex) throws SQLException { - return callableStatement.getArray(parameterIndex); - } - - @Override - public Date getDate(int parameterIndex, Calendar cal) throws SQLException { - return callableStatement.getDate(parameterIndex, cal); - } - - @Override - public Time getTime(int parameterIndex, Calendar cal) throws SQLException { - return callableStatement.getTime(parameterIndex, cal); - } - - @Override - public Timestamp getTimestamp(int parameterIndex, Calendar cal) throws SQLException { - return callableStatement.getTimestamp(parameterIndex, cal); - } - - @Override - public void registerOutParameter(int parameterIndex, int sqlType, String typeName) throws SQLException { - callableStatement.registerOutParameter(parameterIndex, sqlType, typeName); - } - - @Override - public void registerOutParameter(String parameterName, int sqlType) throws SQLException { - callableStatement.registerOutParameter(parameterName, sqlType); - } - - @Override - public void registerOutParameter(String parameterName, int sqlType, int scale) throws SQLException { - callableStatement.registerOutParameter(parameterName, sqlType, scale); - } - - @Override - public void registerOutParameter(String parameterName, int sqlType, String typeName) throws SQLException { - callableStatement.registerOutParameter(parameterName, sqlType, typeName); - } - - @Override - public URL getURL(int parameterIndex) throws SQLException { - return callableStatement.getURL(parameterIndex); - } - - @Override - public void setURL(String parameterName, URL val) throws SQLException { - callableStatement.setURL(parameterName, val); - } - - @Override - public void setNull(String parameterName, int sqlType) throws SQLException { - callableStatement.setNull(parameterName, sqlType); - } - - @Override - public void setBoolean(String parameterName, boolean x) throws SQLException { - callableStatement.setBoolean(parameterName, x); - } - - @Override - public void setByte(String parameterName, byte x) throws SQLException { - callableStatement.setByte(parameterName, x); - } - - @Override - public void setShort(String parameterName, short x) throws SQLException { - callableStatement.setShort(parameterName, x); - } - - @Override - public void setInt(String parameterName, int x) throws SQLException { - callableStatement.setInt(parameterName, x); - } - - @Override - public void setLong(String parameterName, long x) throws SQLException { - callableStatement.setLong(parameterName, x); - } - - @Override - public void setFloat(String parameterName, float x) throws SQLException { - callableStatement.setFloat(parameterName, x); - } - - @Override - public void setDouble(String parameterName, double x) throws SQLException { - callableStatement.setDouble(parameterName, x); - } - - @Override - public void setBigDecimal(String parameterName, BigDecimal x) throws SQLException { - callableStatement.setBigDecimal(parameterName, x); - } - - @Override - public void setString(String parameterName, String x) throws SQLException { - callableStatement.setString(parameterName, x); - } - - @Override - public void setBytes(String parameterName, byte[] x) throws SQLException { - callableStatement.setBytes(parameterName, x); - } - - @Override - public void setDate(String parameterName, Date x) throws SQLException { - callableStatement.setDate(parameterName, x); - } - - @Override - public void setTime(String parameterName, Time x) throws SQLException { - callableStatement.setTime(parameterName, x); - } - - @Override - public void setTimestamp(String parameterName, Timestamp x) throws SQLException { - callableStatement.setTimestamp(parameterName, x); - } - - @Override - public void setAsciiStream(String parameterName, InputStream x, int length) throws SQLException { - callableStatement.setAsciiStream(parameterName, x, length); - } - - @Override - public void setBinaryStream(String parameterName, InputStream x, int length) throws SQLException { - callableStatement.setBinaryStream(parameterName, x, length); - } - - @Override - public void setObject(String parameterName, Object x, int targetSqlType, int scale) throws SQLException { - callableStatement.setObject(parameterName, x, targetSqlType, scale); - } - - @Override - public void setObject(String parameterName, Object x, int targetSqlType) throws SQLException { - callableStatement.setObject(parameterName, x, targetSqlType); - } - - @Override - public void setObject(String parameterName, Object x) throws SQLException { - callableStatement.setObject(parameterName, x); - } - - @Override - public void setCharacterStream(String parameterName, Reader reader, int length) throws SQLException { - callableStatement.setCharacterStream(parameterName, reader, length); - } - - @Override - public void setDate(String parameterName, Date x, Calendar cal) throws SQLException { - callableStatement.setDate(parameterName, x, cal); - } - - @Override - public void setTime(String parameterName, Time x, Calendar cal) throws SQLException { - callableStatement.setTime(parameterName, x, cal); - } - - @Override - public void setTimestamp(String parameterName, Timestamp x, Calendar cal) throws SQLException { - callableStatement.setTimestamp(parameterName, x, cal); - } - - @Override - public void setNull(String parameterName, int sqlType, String typeName) throws SQLException { - callableStatement.setNull(parameterName, sqlType, typeName); - } - - @Override - public String getString(String parameterName) throws SQLException { - return callableStatement.getString(parameterName); - } - - @Override - public boolean getBoolean(String parameterName) throws SQLException { - return callableStatement.getBoolean(parameterName); - } - - @Override - public byte getByte(String parameterName) throws SQLException { - return callableStatement.getByte(parameterName); - } - - @Override - public short getShort(String parameterName) throws SQLException { - return callableStatement.getShort(parameterName); - } - - @Override - public int getInt(String parameterName) throws SQLException { - return callableStatement.getInt(parameterName); - } - - @Override - public long getLong(String parameterName) throws SQLException { - return callableStatement.getLong(parameterName); - } - - @Override - public float getFloat(String parameterName) throws SQLException { - return callableStatement.getFloat(parameterName); - } - - @Override - public double getDouble(String parameterName) throws SQLException { - return callableStatement.getDouble(parameterName); - } - - @Override - public byte[] getBytes(String parameterName) throws SQLException { - return callableStatement.getBytes(parameterName); - } - - @Override - public Date getDate(String parameterName) throws SQLException { - return callableStatement.getDate(parameterName); - } - - @Override - public Time getTime(String parameterName) throws SQLException { - return callableStatement.getTime(parameterName); - } - - @Override - public Timestamp getTimestamp(String parameterName) throws SQLException { - return callableStatement.getTimestamp(parameterName); - } - - @Override - public Object getObject(String parameterName) throws SQLException { - return callableStatement.getObject(parameterName); - } - - @Override - public BigDecimal getBigDecimal(String parameterName) throws SQLException { - return callableStatement.getBigDecimal(parameterName); - } - - @Override - public Object getObject(String parameterName, Map > map) throws SQLException { - return callableStatement.getObject(parameterName, map); - } - - @Override - public Ref getRef(String parameterName) throws SQLException { - return callableStatement.getRef(parameterName); - } - - @Override - public Blob getBlob(String parameterName) throws SQLException { - return callableStatement.getBlob(parameterName); - } - - @Override - public Clob getClob(String parameterName) throws SQLException { - return callableStatement.getClob(parameterName); - } - - @Override - public Array getArray(String parameterName) throws SQLException { - return callableStatement.getArray(parameterName); - } - - @Override - public Date getDate(String parameterName, Calendar cal) throws SQLException { - return callableStatement.getDate(parameterName, cal); - } - - @Override - public Time getTime(String parameterName, Calendar cal) throws SQLException { - return callableStatement.getTime(parameterName, cal); - } - - @Override - public Timestamp getTimestamp(String parameterName, Calendar cal) throws SQLException { - return callableStatement.getTimestamp(parameterName, cal); - } - - @Override - public URL getURL(String parameterName) throws SQLException { - return callableStatement.getURL(parameterName); - } - - @Override - public RowId getRowId(int parameterIndex) throws SQLException { - return callableStatement.getRowId(parameterIndex); - } - - @Override - public RowId getRowId(String parameterName) throws SQLException { - return callableStatement.getRowId(parameterName); - } - - @Override - public void setRowId(String parameterName, RowId x) throws SQLException { - callableStatement.setRowId(parameterName, x); - } - - @Override - public void setNString(String parameterName, String value) throws SQLException { - callableStatement.setNString(parameterName, value); - } - - @Override - public void setNCharacterStream(String parameterName, Reader value, long length) throws SQLException { - callableStatement.setNCharacterStream(parameterName, value, length); - } - - @Override - public void setNClob(String parameterName, NClob value) throws SQLException { - callableStatement.setNClob(parameterName, value); - } - - @Override - public void setClob(String parameterName, Reader reader, long length) throws SQLException { - callableStatement.setClob(parameterName, reader, length); - } - - @Override - public void setBlob(String parameterName, InputStream inputStream, long length) throws SQLException { - callableStatement.setBlob(parameterName, inputStream, length); - } - - @Override - public void setNClob(String parameterName, Reader reader, long length) throws SQLException { - callableStatement.setNClob(parameterName, reader, length); - } - - @Override - public NClob getNClob(int parameterIndex) throws SQLException { - return callableStatement.getNClob(parameterIndex); - } - - @Override - public NClob getNClob(String parameterName) throws SQLException { - return callableStatement.getNClob(parameterName); - } - - @Override - public void setSQLXML(String parameterName, SQLXML xmlObject) throws SQLException { - callableStatement.setSQLXML(parameterName, xmlObject); - } - - @Override - public SQLXML getSQLXML(int parameterIndex) throws SQLException { - return callableStatement.getSQLXML(parameterIndex); - } - - @Override - public SQLXML getSQLXML(String parameterName) throws SQLException { - return callableStatement.getSQLXML(parameterName); - } - - @Override - public String getNString(int parameterIndex) throws SQLException { - return callableStatement.getNString(parameterIndex); - } - - @Override - public String getNString(String parameterName) throws SQLException { - return callableStatement.getNString(parameterName); - } - - @Override - public Reader getNCharacterStream(int parameterIndex) throws SQLException { - return callableStatement.getNCharacterStream(parameterIndex); - } - - @Override - public Reader getNCharacterStream(String parameterName) throws SQLException { - return callableStatement.getNCharacterStream(parameterName); - } - - @Override - public Reader getCharacterStream(int parameterIndex) throws SQLException { - return callableStatement.getCharacterStream(parameterIndex); - } - - @Override - public Reader getCharacterStream(String parameterName) throws SQLException { - return callableStatement.getCharacterStream(parameterName); - } - - @Override - public void setBlob(String parameterName, Blob x) throws SQLException { - callableStatement.setBlob(parameterName, x); - } - - @Override - public void setClob(String parameterName, Clob x) throws SQLException { - callableStatement.setClob(parameterName, x); - } - - @Override - public void setAsciiStream(String parameterName, InputStream x, long length) throws SQLException { - callableStatement.setAsciiStream(parameterName, x, length); - } - - @Override - public void setBinaryStream(String parameterName, InputStream x, long length) throws SQLException { - callableStatement.setBinaryStream(parameterName, x, length); - } - - @Override - public void setCharacterStream(String parameterName, Reader reader, long length) throws SQLException { - callableStatement.setCharacterStream(parameterName, reader, length); - } - - @Override - public void setAsciiStream(String parameterName, InputStream x) throws SQLException { - callableStatement.setAsciiStream(parameterName, x); - } - - @Override - public void setBinaryStream(String parameterName, InputStream x) throws SQLException { - callableStatement.setBinaryStream(parameterName, x); - } - - @Override - public void setCharacterStream(String parameterName, Reader reader) throws SQLException { - callableStatement.setCharacterStream(parameterName, reader); - } - - @Override - public void setNCharacterStream(String parameterName, Reader value) throws SQLException { - callableStatement.setNCharacterStream(parameterName, value); - } - - @Override - public void setClob(String parameterName, Reader reader) throws SQLException { - callableStatement.setClob(parameterName, reader); - } - - @Override - public void setBlob(String parameterName, InputStream inputStream) throws SQLException { - callableStatement.setBlob(parameterName, inputStream); - } - - @Override - public void setNClob(String parameterName, Reader reader) throws SQLException { - callableStatement.setNClob(parameterName, reader); - } - - @Override - public T getObject(int parameterIndex, Class type) throws SQLException { - return callableStatement.getObject(parameterIndex, type); - } - - @Override - public T getObject(String parameterName, Class type) throws SQLException { - return callableStatement.getObject(parameterName, type); - } -} - - diff --git a/jodd-db/src/main/java/jodd/db/debug/LoggablePreparedStatement.java b/jodd-db/src/main/java/jodd/db/debug/LoggablePreparedStatement.java deleted file mode 100644 index 992b07285..000000000 --- a/jodd-db/src/main/java/jodd/db/debug/LoggablePreparedStatement.java +++ /dev/null @@ -1,387 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.debug; - -import java.io.InputStream; -import java.io.Reader; -import java.math.BigDecimal; -import java.net.URL; -import java.sql.Array; -import java.sql.Blob; -import java.sql.Clob; -import java.sql.Date; -import java.sql.NClob; -import java.sql.ParameterMetaData; -import java.sql.PreparedStatement; -import java.sql.Ref; -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; -import java.sql.RowId; -import java.sql.SQLException; -import java.sql.SQLXML; -import java.sql.Time; -import java.sql.Timestamp; -import java.util.Calendar; - -/** - * Factory for loggable prepared statements - a PreparedStatement
with added logging capability. - *- * In addition to the methods declared in
PreparedStatement
, - *LoggablePreparedStatement
provides a method {@link #getQueryString} that can be used to get - * the query string in a format suitable for logging. - *- * Should not be used in production! - */ -@SuppressWarnings("MagicConstant") -public class LoggablePreparedStatement extends BaseLoggableStatement
implements PreparedStatement { - - public LoggablePreparedStatement(final PreparedStatement wrappedStatement, final String sqlTemplate) { - super(wrappedStatement, sqlTemplate); - } - - @Override - public ResultSet executeQuery() throws SQLException { - return wrappedStatement.executeQuery(); - } - - @Override - public int executeUpdate() throws SQLException { - return wrappedStatement.executeUpdate(); - } - - @Override - public void setNull(int parameterIndex, int sqlType) throws SQLException { - saveQueryParamValue(parameterIndex, null); - wrappedStatement.setNull(parameterIndex, sqlType); - } - - @Override - public void setBoolean(int parameterIndex, boolean x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setBoolean(parameterIndex, x); - } - - @Override - public void setByte(int parameterIndex, byte x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setByte(parameterIndex, x); - } - - @Override - public void setShort(int parameterIndex, short x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setShort(parameterIndex, x); - } - - @Override - public void setInt(int parameterIndex, int x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setInt(parameterIndex, x); - } - - @Override - public void setLong(int parameterIndex, long x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setLong(parameterIndex, x); - } - - @Override - public void setFloat(int parameterIndex, float x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setFloat(parameterIndex, x); - } - - @Override - public void setDouble(int parameterIndex, double x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setDouble(parameterIndex, x); - } - - @Override - public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setBigDecimal(parameterIndex, x); - } - - @Override - public void setString(int parameterIndex, String x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setString(parameterIndex, x); - } - - @Override - public void setBytes(int parameterIndex, byte[] x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setBytes(parameterIndex, x); - } - - @Override - public void setDate(int parameterIndex, Date x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setDate(parameterIndex, x); - } - - @Override - public void setTime(int parameterIndex, Time x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setTime(parameterIndex, x); - } - - @Override - public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setTimestamp(parameterIndex, x); - } - - @Override - public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setAsciiStream(parameterIndex, x); - } - - @Override - @Deprecated - public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setUnicodeStream(parameterIndex, x, length); - } - - @Override - public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setBinaryStream(parameterIndex, x, length); - } - - @Override - public void clearParameters() throws SQLException { - wrappedStatement.clearParameters(); - } - - @Override - public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setObject(parameterIndex, x, targetSqlType); - } - - @Override - public void setObject(int parameterIndex, Object x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setObject(parameterIndex, x); - } - - @Override - public boolean execute() throws SQLException { - return wrappedStatement.execute(); - } - - @Override - public void addBatch() throws SQLException { - wrappedStatement.addBatch(); - } - - @Override - public void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException { - saveQueryParamValue(parameterIndex, reader); - wrappedStatement.setCharacterStream(parameterIndex, reader, length); - } - - @Override - public void setRef(int parameterIndex, Ref x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setRef(parameterIndex, x); - } - - @Override - public void setBlob(int parameterIndex, Blob x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setBlob(parameterIndex, x); - } - - @Override - public void setClob(int parameterIndex, Clob x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setClob(parameterIndex, x); - } - - @Override - public void setArray(int parameterIndex, Array x) throws SQLException { - wrappedStatement.setArray(parameterIndex, x); - } - - @Override - public ResultSetMetaData getMetaData() throws SQLException { - return wrappedStatement.getMetaData(); - } - - @Override - public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setDate(parameterIndex, x, cal); - } - - @Override - public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setTime(parameterIndex, x, cal); - } - - @Override - public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setTimestamp(parameterIndex, x, cal); - } - - @Override - public void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException { - saveQueryParamValue(parameterIndex, null); - wrappedStatement.setNull(parameterIndex, sqlType, typeName); - } - - @Override - public void setURL(int parameterIndex, URL x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setURL(parameterIndex, x); - } - - @Override - public ParameterMetaData getParameterMetaData() throws SQLException { - return wrappedStatement.getParameterMetaData(); - } - - @Override - public void setRowId(int parameterIndex, RowId x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setRowId(parameterIndex, x); - } - - @Override - public void setNString(int parameterIndex, String value) throws SQLException { - saveQueryParamValue(parameterIndex, value); - wrappedStatement.setNString(parameterIndex, value); - } - - @Override - public void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException { - saveQueryParamValue(parameterIndex, value); - wrappedStatement.setNCharacterStream(parameterIndex, value, length); - } - - @Override - public void setNClob(int parameterIndex, NClob value) throws SQLException { - saveQueryParamValue(parameterIndex, value); - wrappedStatement.setNClob(parameterIndex, value); - } - - @Override - public void setClob(int parameterIndex, Reader reader, long length) throws SQLException { - saveQueryParamValue(parameterIndex, reader); - wrappedStatement.setClob(parameterIndex, reader, length); - } - - @Override - public void setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException { - saveQueryParamValue(parameterIndex, inputStream); - wrappedStatement.setBlob(parameterIndex, inputStream, length); - } - - @Override - public void setNClob(int parameterIndex, Reader reader, long length) throws SQLException { - saveQueryParamValue(parameterIndex, reader); - wrappedStatement.setNClob(parameterIndex, reader, length); - } - - @Override - public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException { - saveQueryParamValue(parameterIndex, xmlObject); - wrappedStatement.setSQLXML(parameterIndex, xmlObject); - } - - @Override - public void setObject(int parameterIndex, Object x, int targetSqlType, int scaleOrLength) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setObject(parameterIndex, x, targetSqlType, scaleOrLength); - } - - @Override - public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setAsciiStream(parameterIndex, x, length); - } - - @Override - public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setBinaryStream(parameterIndex, x, length); - } - - @Override - public void setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException { - saveQueryParamValue(parameterIndex, reader); - wrappedStatement.setCharacterStream(parameterIndex, reader, length); - } - - @Override - public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setAsciiStream(parameterIndex, x); - } - - @Override - public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setBinaryStream(parameterIndex, x); - } - - @Override - public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException { - saveQueryParamValue(parameterIndex, reader); - wrappedStatement.setCharacterStream(parameterIndex, reader); - } - - @Override - public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException { - saveQueryParamValue(parameterIndex, value); - wrappedStatement.setNCharacterStream(parameterIndex, value); - } - - @Override - public void setClob(int parameterIndex, Reader reader) throws SQLException { - saveQueryParamValue(parameterIndex, reader); - wrappedStatement.setClob(parameterIndex, reader); - } - - @Override - public void setBlob(int parameterIndex, InputStream inputStream) throws SQLException { - saveQueryParamValue(parameterIndex, inputStream); - wrappedStatement.setBlob(parameterIndex, inputStream); - } - - @Override - public void setNClob(int parameterIndex, Reader reader) throws SQLException { - saveQueryParamValue(parameterIndex, reader); - wrappedStatement.setNClob(parameterIndex, reader); - } -} diff --git a/jodd-db/src/main/java/jodd/db/debug/package-info.java b/jodd-db/src/main/java/jodd/db/debug/package-info.java deleted file mode 100644 index 880542698..000000000 --- a/jodd-db/src/main/java/jodd/db/debug/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Various database debugging tools. Not for use in production. - */ -package jodd.db.debug; \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/jtx/DbJtxResourceManager.java b/jodd-db/src/main/java/jodd/db/jtx/DbJtxResourceManager.java deleted file mode 100644 index 9b834356d..000000000 --- a/jodd-db/src/main/java/jodd/db/jtx/DbJtxResourceManager.java +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.jtx; - -import jodd.db.DbSession; -import jodd.db.connection.ConnectionProvider; -import jodd.jtx.JtxException; -import jodd.jtx.JtxResourceManager; -import jodd.jtx.JtxTransactionMode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Database {@link jodd.jtx.JtxResourceManager} manages life-cycle of {@link jodd.db.DbSession} resources. - * Also acts as an adapter of resource object (of any type) and JTX engine. - * - * Transaction resources may be of any type. The only thing what is important is that resource must be - * aware of its transactional state - is it in no-transactional mode (i.e. auto-commit), or under the transaction. - */ -public class DbJtxResourceManager implements JtxResourceManager
{ - - private static final Logger log = LoggerFactory.getLogger(DbJtxResourceManager.class); - - protected final ConnectionProvider connectionProvider; - - /** - * Creates resource manager. - */ - public DbJtxResourceManager(final ConnectionProvider connectionProvider) { - this.connectionProvider = connectionProvider; - } - - /** - * {@inheritDoc} - */ - public Class getResourceType() { - return DbSession.class; - } - - // ---------------------------------------------------------------- resource manager - - /** - * {@inheritDoc} - */ - public DbSession beginTransaction(final JtxTransactionMode jtxMode, final boolean active) { - final DbSession session = new DbSession(connectionProvider); - if (active) { - log.debug("begin jtx"); - - session.beginTransaction(JtxDbUtil.convertToDbMode(jtxMode)); - } - return session; - } - - /** - * {@inheritDoc} - */ - public void commitTransaction(final DbSession resource) { - if (resource.isTransactionActive()) { - log.debug("commit jtx"); - - resource.commitTransaction(); - } - resource.closeSession(); - } - - /** - * {@inheritDoc} - */ - public void rollbackTransaction(final DbSession resource) { - try { - if (resource.isTransactionActive()) { - log.debug("rollback tx"); - - resource.rollbackTransaction(); - } - } catch (final Exception ex) { - throw new JtxException(ex); - } finally { - resource.closeSession(); - } - } - - /** - * {@inheritDoc} - */ - public void close() { - connectionProvider.close(); - } - -} diff --git a/jodd-db/src/main/java/jodd/db/jtx/DbJtxSessionProvider.java b/jodd-db/src/main/java/jodd/db/jtx/DbJtxSessionProvider.java deleted file mode 100644 index a5a37fe77..000000000 --- a/jodd-db/src/main/java/jodd/db/jtx/DbJtxSessionProvider.java +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.jtx; - -import jodd.db.DbSession; -import jodd.db.DbSessionProvider; -import jodd.db.DbSqlException; -import jodd.jtx.JtxTransactionManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Returns session from the db {@link JtxTransactionManager transaction manager}, - * like {@link DbJtxTransactionManager}. - */ -public class DbJtxSessionProvider implements DbSessionProvider { - - private static final Logger log = LoggerFactory.getLogger(DbJtxSessionProvider.class); - - protected final JtxTransactionManager jtxTxManager; - - /** - * Creates new JTX session provider. - */ - public DbJtxSessionProvider(final JtxTransactionManager txManager) { - this.jtxTxManager = txManager; - } - - /** - * Returns session from JTX transaction manager and started transaction. - */ - @Override - public DbSession getDbSession() { - log.debug("Requesting db TX manager session"); - - final DbJtxTransaction jtx = (DbJtxTransaction) jtxTxManager.getTransaction(); - - if (jtx == null) { - throw new DbSqlException( - "No transaction is in progress and DbSession can't be provided. " + - "It seems that transaction manager is not used to begin a transaction."); - } - - return jtx.requestResource(); - } - -} diff --git a/jodd-db/src/main/java/jodd/db/jtx/DbJtxTransaction.java b/jodd-db/src/main/java/jodd/db/jtx/DbJtxTransaction.java deleted file mode 100644 index c0f0802bb..000000000 --- a/jodd-db/src/main/java/jodd/db/jtx/DbJtxTransaction.java +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.jtx; - -import jodd.db.DbSession; -import jodd.jtx.JtxTransaction; -import jodd.jtx.JtxTransactionManager; -import jodd.jtx.JtxTransactionMode; - -/** - * {@link JtxTransaction} extension that simplifies beginning of the transaction since - * related {@link DbJtxTransactionManager} allows only one resource type. - */ -public class DbJtxTransaction extends JtxTransaction { - - protected DbJtxTransaction(final JtxTransactionManager txManager, final JtxTransactionMode mode, final Object scope, final boolean active) { - super(txManager, mode, scope, active); - } - - public DbSession requestResource() { - return requestResource(DbSession.class); - } - -} diff --git a/jodd-db/src/main/java/jodd/db/jtx/DbJtxTransactionManager.java b/jodd-db/src/main/java/jodd/db/jtx/DbJtxTransactionManager.java deleted file mode 100644 index bfa397e2b..000000000 --- a/jodd-db/src/main/java/jodd/db/jtx/DbJtxTransactionManager.java +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.jtx; - -import jodd.db.connection.ConnectionProvider; -import jodd.jtx.JtxTransaction; -import jodd.jtx.JtxTransactionManager; -import jodd.jtx.JtxTransactionMode; - -/** - * {@link jodd.jtx.JtxTransactionManager} that uses only one JTX db resource type. - * Usually, applications have only one transactional resource type - the database. - * This manager just simplifies the usage, nothing more. - * @see jodd.jtx.JtxTransactionManager - */ -public class DbJtxTransactionManager extends JtxTransactionManager { - - /** - * Creates db jtx manager and registers provided {@link DbJtxResourceManager}. - */ - public DbJtxTransactionManager(final DbJtxResourceManager resourceManager) { - setMaxResourcesPerTransaction(1); - setSingleResourceManager(true); - super.registerResourceManager(resourceManager); - - } - - /** - * Creates db jtx manager and registers new {@link DbJtxResourceManager}. - */ - public DbJtxTransactionManager(final ConnectionProvider connectionProvider) { - this(new DbJtxResourceManager(connectionProvider)); - } - - /** - * {@inheritDoc} - */ - @Override - public DbJtxTransaction requestTransaction(final JtxTransactionMode mode) { - return (DbJtxTransaction) super.requestTransaction(mode, null); - } - - /** - * {@inheritDoc} - */ - @Override - public DbJtxTransaction requestTransaction(final JtxTransactionMode mode, final Object scope) { - return (DbJtxTransaction) super.requestTransaction(mode, scope); - } - - /** - * Builds new transaction instance. - */ - @Override - protected JtxTransaction createNewTransaction(final JtxTransactionMode tm, final Object scope, final boolean active) { - return new DbJtxTransaction(this, tm, scope, active); - } - -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/jtx/JtxDbUtil.java b/jodd-db/src/main/java/jodd/db/jtx/JtxDbUtil.java deleted file mode 100644 index 0dd936a47..000000000 --- a/jodd-db/src/main/java/jodd/db/jtx/JtxDbUtil.java +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.jtx; - -import jodd.db.DbTransactionMode; -import jodd.jtx.JtxTransactionMode; - -/** - * Helpers for jtx db. - */ -public class JtxDbUtil { - - /** - * Converter JTX transaction mode to DB transaction mode. - */ - public static DbTransactionMode convertToDbMode(final JtxTransactionMode txMode) { - final int isolation; - switch (txMode.getIsolationLevel()) { - case ISOLATION_DEFAULT: isolation = DbTransactionMode.ISOLATION_DEFAULT; break; - case ISOLATION_NONE: isolation = DbTransactionMode.ISOLATION_NONE; break; - case ISOLATION_READ_COMMITTED: isolation = DbTransactionMode.ISOLATION_READ_COMMITTED; break; - case ISOLATION_READ_UNCOMMITTED: isolation = DbTransactionMode.ISOLATION_READ_UNCOMMITTED; break; - case ISOLATION_REPEATABLE_READ: isolation = DbTransactionMode.ISOLATION_REPEATABLE_READ; break; - case ISOLATION_SERIALIZABLE: isolation = DbTransactionMode.ISOLATION_SERIALIZABLE; break; - default: - throw new IllegalArgumentException(); - } - return new DbTransactionMode(isolation, txMode.isReadOnly()); - } -} diff --git a/jodd-db/src/main/java/jodd/db/jtx/package-info.java b/jodd-db/src/main/java/jodd/db/jtx/package-info.java deleted file mode 100644 index ba6691d2b..000000000 --- a/jodd-db/src/main/java/jodd/db/jtx/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Database extension for propagated transactions. - */ -package jodd.db.jtx; \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/oom/AutomagicDbOomConfigurator.java b/jodd-db/src/main/java/jodd/db/oom/AutomagicDbOomConfigurator.java deleted file mode 100644 index fff733e24..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/AutomagicDbOomConfigurator.java +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom; - -import jodd.db.oom.meta.DbTable; -import jodd.io.findfile.ClassScanner; -import jodd.util.Consumers; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.function.Consumer; - -/** - * Auto-magically scans classpath for domain objects annotated with DbOom annotations. - */ -public class AutomagicDbOomConfigurator { - - private static final Logger log = LoggerFactory.getLogger(AutomagicDbOomConfigurator.class); - - protected final static byte[] DB_TABLE_ANNOTATION_BYTES = ClassScanner.bytecodeSignatureOfType(DbTable.class); - protected final boolean registerAsEntities; - protected final DbEntityManager dbEntityManager; - private final Consumers classScannerConsumers = new Consumers<>(); - - public AutomagicDbOomConfigurator(final DbEntityManager dbEntityManager, final boolean registerAsEntities) { - this.dbEntityManager = dbEntityManager; - this.registerAsEntities = registerAsEntities; - } - - public AutomagicDbOomConfigurator withScanner(final Consumer scannerConsumer) { - classScannerConsumers.add(scannerConsumer); - return this; - } - - - /** - * Configures {@link DbEntityManager} with specified class path. - */ - public void configure() { - long elapsed = System.currentTimeMillis(); - - final ClassScanner classScanner = new ClassScanner(); - - classScanner.detectEntriesMode(true); - classScanner.scanDefaultClasspath(); - - classScannerConsumers.accept(classScanner); - - registerAsConsumer(classScanner); - - try { - classScanner.start(); - } catch (final Exception ex) { - throw new DbOomException("Scan classpath error", ex); - } - elapsed = System.currentTimeMillis() - elapsed; - if (log.isInfoEnabled()) { - log.info("DbEntityManager configured in " + elapsed + "ms. Total entities: " + dbEntityManager.getTotalNames()); - } - } - - /** - * Registers a class consumer that registers only those annotated with {@link DbTable}. - * Because of performance purposes, classes are not dynamically loaded; instead, their - * file content is examined. - */ - public void registerAsConsumer(final ClassScanner classScanner) { - classScanner.registerEntryConsumer(classPathEntry -> { - if (!classPathEntry.isTypeSignatureInUse(DB_TABLE_ANNOTATION_BYTES)) { - return; - } - - final Class> beanClass; - try { - beanClass = classPathEntry.loadClass(); - } catch (final ClassNotFoundException cnfex) { - throw new DbOomException("Entry class not found: " + classPathEntry.name(), cnfex); - } - - if (beanClass == null) { - return; - } - - final DbTable dbTable = beanClass.getAnnotation(DbTable.class); - - if (dbTable == null) { - return; - } - - if (registerAsEntities) { - dbEntityManager.registerEntity(beanClass); - } else { - dbEntityManager.registerType(beanClass); - } - }); - } - -} diff --git a/jodd-db/src/main/java/jodd/db/oom/ColumnAliasType.java b/jodd-db/src/main/java/jodd/db/oom/ColumnAliasType.java deleted file mode 100644 index 653e1a7d0..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/ColumnAliasType.java +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom; - -/** - * Various column alias types. Sometimes, when database JDBC driver does not - * support table names in ResultSet metadata, it might be useful to include - * table name or a reference in the column name, separated by some separator. - * - * Using TABLE_NAME type might be dangerous, since most databases (including Oracle) - * has some maximum length for column names, so adding table name prefix might - * be too much;) - *
- * Column types are usually used internally by SQL generators (see: {@link DbSqlGenerator}). - */ -public enum ColumnAliasType { - - TABLE_NAME(1), // table_name
column_name - TABLE_REFERENCE(2), // table_reference column_name - COLUMN_CODE(3); // col_ _ - - int value; - - ColumnAliasType(final int aliasType) { - this.value = aliasType; - } -} diff --git a/jodd-db/src/main/java/jodd/db/oom/ColumnData.java b/jodd-db/src/main/java/jodd/db/oom/ColumnData.java deleted file mode 100644 index 281d64f66..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/ColumnData.java +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom; - -/** - * Column data. - */ -public class ColumnData { - - private final String tableName; - private final String columnName; - - public ColumnData(final String tableName) { - this.tableName = tableName; - this.columnName = null; - } - - public ColumnData(final String tableName, final String columnName) { - this.tableName = tableName; - this.columnName = columnName; - } - - /** - * Returns table name for this column. - */ - public String getTableName() { - return tableName; - } - - /** - * Returns column name for this column. - */ - public String getColumnName() { - return columnName; - } - -} diff --git a/jodd-db/src/main/java/jodd/db/oom/DbEntityColumnDescriptor.java b/jodd-db/src/main/java/jodd/db/oom/DbEntityColumnDescriptor.java deleted file mode 100644 index e1a437748..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/DbEntityColumnDescriptor.java +++ /dev/null @@ -1,180 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom; - -import jodd.db.type.SqlType; -import jodd.util.StringUtil; - -/** - * Column descriptors. - */ -public class DbEntityColumnDescriptor implements Comparable { - - protected final DbEntityDescriptor dbEntityDescriptor; - protected final String columnName; - protected final String columnNameForQuery; - protected final String propertyName; - protected final Class propertyType; - protected final boolean isId; - protected final Class extends SqlType> sqlTypeClass; - protected int dbSqlType = SqlType.DB_SQLTYPE_UNKNOWN; - - public DbEntityColumnDescriptor( - final DbEntityDescriptor ded, - final String columnName, - final String fieldName, - final Class fieldType, - final boolean isId, - final Class extends SqlType> sqlTypeClass) { - - this.dbEntityDescriptor = ded; - this.propertyName = fieldName; - this.propertyType = fieldType; - this.isId = isId; - this.sqlTypeClass = sqlTypeClass; - - this.columnNameForQuery = columnName; - - if (StringUtil.detectQuoteChar(columnNameForQuery) != 0) { - this.columnName = StringUtil.substring(columnNameForQuery, 1, -1); - } - else { - this.columnName = columnNameForQuery; - } - } - - /** - * Returns {@link jodd.db.oom.DbEntityDescriptor} that this column description belongs to. - */ - public DbEntityDescriptor getDbEntityDescriptor() { - return dbEntityDescriptor; - } - - /** - * Returns column name. - */ - public String getColumnName() { - return columnName; - } - - /** - * Returns column name to be used in the generated sql. - */ - public String getColumnNameForQuery() { - return columnNameForQuery; - } - - /** - * Returns property name. - */ - public String getPropertyName() { - return propertyName; - } - - /** - * Returns property type. - */ - public Class getPropertyType() { - return propertyType; - } - - /** - * Returns true
if column is ID column. - */ - public boolean isId() { - return isId; - } - - /** - * Returns SqlType ornull
for default type. - */ - public Class extends SqlType> getSqlTypeClass() { - return sqlTypeClass; - } - - /** - * Returns db sql type. Important: available only after first saving of column value - * to database! - */ - public int getDbSqlType() { - return dbSqlType; - } - - /** - * Updates db sql type if not already set. - */ - public void updateDbSqlType(final int dbSqlType) { - if (this.dbSqlType == SqlType.DB_SQLTYPE_UNKNOWN) { - this.dbSqlType = dbSqlType; - } - } - - // ---------------------------------------------------------------- comparable - - /** - * Compares two column descriptors. Identity columns should be the first on the list. - * Each group then will be sorted by column name. - */ - @Override - public int compareTo(final Object o) { - DbEntityColumnDescriptor that = (DbEntityColumnDescriptor) o; - if (this.isId != that.isId) { - return this.isId ? -1 : 1; // IDs should be the first in the array - } - return this.columnName.compareTo(that.columnName); - } - - // ---------------------------------------------------------------- equals and hash - - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; - } - if (this.getClass() != o.getClass()) { - return false; - } - DbEntityColumnDescriptor that = (DbEntityColumnDescriptor) o; - return columnName.equals(that.columnName); - } - - @Override - public int hashCode() { - return columnName.hashCode(); - } - - // ---------------------------------------------------------------- to string - - - @Override - public String toString() { - return "DbEntityColumnDescriptor{" + - "columnName='" + columnName + '\'' + - ", propertyName='" + propertyName + '\'' + - ", isId=" + isId + - '}'; - } -} diff --git a/jodd-db/src/main/java/jodd/db/oom/DbEntityDescriptor.java b/jodd-db/src/main/java/jodd/db/oom/DbEntityDescriptor.java deleted file mode 100644 index 825b2b53a..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/DbEntityDescriptor.java +++ /dev/null @@ -1,341 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom; - -import jodd.bean.BeanUtil; -import jodd.db.oom.naming.ColumnNamingStrategy; -import jodd.db.oom.naming.TableNamingStrategy; -import jodd.introspector.ClassIntrospector; -import jodd.introspector.PropertyDescriptor; -import jodd.util.StringPool; -import jodd.util.StringUtil; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; - -/** - * Holds all information about some entity type, such as table name and {@link DbEntityColumnDescriptor columns data}. - */ -public class DbEntityDescriptor{ - - public DbEntityDescriptor( - final Class type, - final String schemaName, - final TableNamingStrategy tableNamingStrategy, - final ColumnNamingStrategy columnNamingStrategy) { - - this.type = type; - this.entityName = type.getSimpleName(); - this.isAnnotated = DbMetaUtil.resolveIsAnnotated(type); - this.schemaName = DbMetaUtil.resolveSchemaName(type, schemaName); - this.columnNamingStrategy = columnNamingStrategy; - this.mappedTypes = DbMetaUtil.resolveMappedTypes(type); - - this.tableNameForQuery = DbMetaUtil.resolveTableName(type, tableNamingStrategy); - - if (StringUtil.detectQuoteChar(tableNameForQuery) != 0) { - this.tableName = StringUtil.substring(tableNameForQuery, 1, -1); - } else { - this.tableName = tableNameForQuery; - } - } - - // ---------------------------------------------------------------- type and table - - private final Class type; - private final String entityName; - private final boolean isAnnotated; - private final String tableName; - private final String tableNameForQuery; - private final String schemaName; - private final ColumnNamingStrategy columnNamingStrategy; - private final Class[] mappedTypes; - - /** - * Returns entity type. - */ - public Class getType() { - return type; - } - - /** - * Returns true
if type is annotated with {@link jodd.db.oom.meta.DbTable}. - */ - public boolean isAnnotated() { - return isAnnotated; - } - - /** - * Returns table name to which the entity is mapped. - */ - public String getTableName() { - return tableName; - } - - /** - * Returns table name to be used when generating queries. - */ - public String getTableNameForQuery() { - return tableNameForQuery; - } - - /** - * Returns type name. - */ - public String getEntityName() { - return entityName; - } - - /** - * Returns schema name ornull
if not available. - */ - public String getSchemaName() { - return schemaName; - } - - /** - * Returns mapped types. - */ - public Class[] getMappedTypes() { - return mappedTypes; - } - - // ---------------------------------------------------------------- columns and fields - - private DbEntityColumnDescriptor[] columnDescriptors; - private DbEntityColumnDescriptor[] idColumnDescriptors; - - /** - * Returns the array of column descriptors. - */ - public DbEntityColumnDescriptor[] getColumnDescriptors() { - init(); - return columnDescriptors; - } - - // ---------------------------------------------------------------- initialization - - /** - * Lazy initialization of descriptor. - */ - protected void init() { - if (columnDescriptors == null) { - resolveColumnsAndProperties(type); - } - } - - /** - * Resolves list of all columns and properties. - */ - private void resolveColumnsAndProperties(final Class type) { - final PropertyDescriptor[] allProperties = ClassIntrospector.get().lookup(type).getAllPropertyDescriptors(); - final ListdecList = new ArrayList<>(allProperties.length); - int idcount = 0; - - final HashSet names = new HashSet<>(allProperties.length); - - for (final PropertyDescriptor propertyDescriptor : allProperties) { - - final DbEntityColumnDescriptor dec = - DbMetaUtil.resolveColumnDescriptors(this, propertyDescriptor, isAnnotated, columnNamingStrategy); - - if (dec != null) { - if (!names.add(dec.getColumnName())) { - throw new DbOomException("Duplicate column name: " + dec.getColumnName()); - } - - decList.add(dec); - - if (dec.isId) { - idcount++; - } - } - } - if (decList.isEmpty()) { - throw new DbOomException("No column mappings in entity: " + type); - } - columnDescriptors = decList.toArray(new DbEntityColumnDescriptor[0]); - Arrays.sort(columnDescriptors); - - // extract ids from sorted list - if (idcount > 0) { - idColumnDescriptors = new DbEntityColumnDescriptor[idcount]; - idcount = 0; - for (final DbEntityColumnDescriptor dec : columnDescriptors) { - if (dec.isId) { - idColumnDescriptors[idcount++] = dec; - } - } - } - } - - // ---------------------------------------------------------------- finders - - /** - * Finds column descriptor by column name. Case is ignored. - */ - public DbEntityColumnDescriptor findByColumnName(final String columnName) { - if (columnName == null) { - return null; - } - init(); - for (final DbEntityColumnDescriptor columnDescriptor : columnDescriptors) { - if (columnDescriptor.columnName.equalsIgnoreCase(columnName)) { - return columnDescriptor; - } - } - return null; - } - /** - * Finds column descriptor by property name. - */ - public DbEntityColumnDescriptor findByPropertyName(final String propertyName) { - if (propertyName == null) { - return null; - } - init(); - for (final DbEntityColumnDescriptor columnDescriptor : columnDescriptors) { - if (columnDescriptor.propertyName.equals(propertyName)) { - return columnDescriptor; - } - } - return null; - } - - - /** - * Returns property name for specified column name. - */ - public String getPropertyName(final String columnName) { - final DbEntityColumnDescriptor dec = findByColumnName(columnName); - return dec == null ? null : dec.propertyName; - } - - /** - * Returns column name for specified property name.. - */ - public String getColumnName(final String propertyName) { - final DbEntityColumnDescriptor dec = findByPropertyName(propertyName); - return dec == null ? null : dec.columnName; - } - - // ---------------------------------------------------------------- column work - - /** - * Returns total number of columns. - */ - public int getColumnsCount() { - init(); - return columnDescriptors.length; - } - - /** - * Returns total number of identity columns. - */ - public int getIdColumnsCount() { - init(); - return idColumnDescriptors == null ? 0 : idColumnDescriptors.length; - } - - /** - * Returns true
if entity has one ID column. - */ - public boolean hasIdColumn() { - return getIdColumnsCount() == 1; - } - - private void ensureSingleIdColumn() { - init(); - if (idColumnDescriptors == null) { - throw new DbOomException("No identity column in entity: " + entityName); - } else if (idColumnDescriptors.length > 1) { - throw new DbOomException("More then one identity column in entity: " + entityName); - } - } - - /** - * Returns the identity column name of column marked as identity. - * Throws an exception if table has composite primary key. - */ - public String getIdColumnName() { - ensureSingleIdColumn(); - return idColumnDescriptors[0].getColumnName(); - } - - /** - * Returns the first property name of column marked as identity. - * Throws an exception if table has composite primary key. - */ - public String getIdPropertyName() { - ensureSingleIdColumn(); - return idColumnDescriptors[0].getPropertyName(); - } - - /** - * Returns ID value for given entity instance. - */ - public Object getIdValue(final E object) { - final String propertyName = getIdPropertyName(); - return BeanUtil.declared.getProperty(object, propertyName); - } - - /** - * Sets ID value for given entity. - */ - public void setIdValue(final E object, final Object value) { - final String propertyName = getIdPropertyName(); - BeanUtil.declared.setProperty(object, propertyName, value); - } - - /** - * Returns unique key for this entity. Returned key - * is built from entity class and id value. - */ - public String getKeyValue(final E object) { - final Object idValue = getIdValue(object); - - final String idValueString = idValue == null ? StringPool.NULL : idValue.toString(); - - return type.getName().concat(StringPool.COLON).concat(idValueString); - } - - // ---------------------------------------------------------------- toString - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder(); - sb.append("DbEntity: "); - if (schemaName != null) { - sb.append(schemaName); - sb.append('.'); - } - sb.append(tableName); - return sb.toString(); - } - -} diff --git a/jodd-db/src/main/java/jodd/db/oom/DbEntityManager.java b/jodd-db/src/main/java/jodd/db/oom/DbEntityManager.java deleted file mode 100644 index 50a9a5afb..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/DbEntityManager.java +++ /dev/null @@ -1,247 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom; - -import jodd.db.oom.naming.ColumnNamingStrategy; -import jodd.db.oom.naming.TableNamingStrategy; -import jodd.util.ClassUtil; -import jodd.util.StringUtil; -import jodd.util.TypeCache; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.HashMap; -import java.util.Map; -import java.util.function.Consumer; - -/** - * DbOom Entity manager. - *- * Important: configure settings before entity registration! - *
- * Mapping definitions are used only by a result set mapper (such as {@link jodd.db.oom.mapper.ResultSetMapper}) - * to lookup for an entity from table name. Table names are read from result-set meta data, for example. - * It is not needed to use mappings at all: in that case just provide entity types during the conversion of - * result set to objects. - */ -public class DbEntityManager { - - private static final Logger log = LoggerFactory.getLogger(DbEntityManager.class); - - private final DbOomConfig dbOomConfig; - - public DbEntityManager(final DbOomConfig dbOomConfig) { - this.dbOomConfig = dbOomConfig; - } - - // ---------------------------------------------------------------- registration - - protected String[] primitiveEntitiesPrefixes = new String[] { - "java.lang.", - "jodd.mutable.", - int.class.getName(), - long.class.getName(), - float.class.getName(), - double.class.getName(), - short.class.getName(), - boolean.class.getName(), - byte.class.getName()}; - - public String[] getPrimitiveEntitiesPrefixes() { - return primitiveEntitiesPrefixes; - } - - /** - * Specifies array of class name prefixes that will be mapped directly to column. - */ - public void setPrimitiveEntitiesPrefixes(final String... primitiveEntitiesPrefixes) { - this.primitiveEntitiesPrefixes = primitiveEntitiesPrefixes; - } - - protected TypeCache
descriptorsMap = TypeCache.createDefault(); - protected Map entityNamesMap = new HashMap<>(); - protected Map tableNamesMap = new NamedValuesHashMap<>(); - - /** - * Lookups {@link DbEntityDescriptor} for some type and registers the type if is new. - * - * Returns
null
for core classes fromjava
run-time packages! - * Some types are not entities, i.e. domain objects. Instead, primitive entities - * are simply mapped to one column. - */ - publicDbEntityDescriptor lookupType(final Class type) { - final String typeName = type.getName(); - if (StringUtil.startsWithOne(typeName, primitiveEntitiesPrefixes) != -1) { - return null; - } - DbEntityDescriptor ded = descriptorsMap.get(type); - if (ded == null) { - ded = registerType(type); - } - return ded; - } - - - /** - * Lookups for {@link jodd.db.oom.DbEntityDescriptor} that was registered with this manager. - * Returns null
if name not found. - */ - public DbEntityDescriptor lookupName(final String typeName) { - return entityNamesMap.get(typeName); - } - - /** - * Lookups for {@link jodd.db.oom.DbEntityDescriptor} that was registered with this manager. - * Returnsnull
if table name not found. Lookup is case-insensitive. - */ - public DbEntityDescriptor lookupTableName(final String tableName) { - return tableNamesMap.get(tableName); - } - - /** - * Registers just type and entity names. Enough for most usages. - */ - publicDbEntityDescriptor registerType(final Class type) { - final DbEntityDescriptor ded = createDbEntityDescriptor(type); - DbEntityDescriptor existing = descriptorsMap.put(type, ded); - - if (log.isDebugEnabled()) { - log.debug("Register " + type.getName() + " as " + ded.getTableName()); - } - - if (existing != null) { - if (ded.getType() == type) { - return ded; - } - throw new DbOomException("Type already registered: " + existing.getType()); - } - - existing = entityNamesMap.put(ded.getEntityName(), ded); - - if (existing != null) { - throw new DbOomException("Name '" + ded.getEntityName() + "' already mapped to an entity: " + existing.getType()); - } - return ded; - } - - /** - * Registers entity. {@link #registerType(Class) Registers types} and table names. - */ - public DbEntityDescriptor registerEntity(final Class type) { - final DbEntityDescriptor ded = registerType(type); - final DbEntityDescriptor existing = tableNamesMap.put(ded.getTableName(), ded); - - if (existing != null) { - if (ded.getType() == type) { - return ded; - } - throw new DbOomException("Entity registration failed! Table '" + ded.getTableName() + "' already mapped to an entity: " + existing.getType()); - } - return ded; - } - - /** - * Registers entity. Existing entity will be removed if exist, so no exception will be thrown. - */ - public DbEntityDescriptor registerEntity(final Class type, final boolean force) { - if (force) { - removeEntity(type); - } - return registerEntity(type); - } - - /** - * Removes entity and returns removed descriptor. - */ - public DbEntityDescriptor removeEntity(final Class type) { - DbEntityDescriptor ded = descriptorsMap.remove(type); - if (ded == null) { - ded = createDbEntityDescriptor(type); - } - entityNamesMap.remove(ded.getEntityName()); - tableNamesMap.remove(ded.getTableName()); - return ded; - } - - /** - * Creates {@link DbEntityDescriptor}. - */ - protected DbEntityDescriptor createDbEntityDescriptor(final Class type) { - final String schemaName = dbOomConfig.getSchemaName(); - final TableNamingStrategy tableNames = dbOomConfig.getTableNames(); - final ColumnNamingStrategy columnNames = dbOomConfig.getColumnNames(); - - return new DbEntityDescriptor<>(type, schemaName, tableNames, columnNames); - } - - // ---------------------------------------------------------------- stats - - /** - * Returns total number of registered entity names. - */ - public int getTotalNames() { - return entityNamesMap.size(); - } - - /** - * Returns total number of registered table names. - */ - public int getTotalTableNames() { - return tableNamesMap.size(); - } - - /** - * Returns total number of registered types. - */ - public int getTotalTypes() { - return descriptorsMap.size(); - } - - /** - * Resets the manager and clears descriptors maps. - */ - public void reset() { - descriptorsMap.clear(); - entityNamesMap.clear(); - tableNamesMap.clear(); - } - - /** - * Creates new entity instances. - */ - public E createEntityInstance(final Class type) { - try { - return ClassUtil.newInstance(type); - } catch (final Exception ex) { - throw new DbOomException(ex); - } - } - - public void forEachEntity(final Consumer consumer) { - descriptorsMap.forEachValue(consumer); - } - -} diff --git a/jodd-db/src/main/java/jodd/db/oom/DbListIterator.java b/jodd-db/src/main/java/jodd/db/oom/DbListIterator.java deleted file mode 100644 index b006d1408..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/DbListIterator.java +++ /dev/null @@ -1,177 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom; - -import jodd.db.oom.mapper.ResultSetMapper; - -import java.util.Arrays; -import java.util.Iterator; -import java.util.NoSuchElementException; - -/** - * Internal result set iterator. - */ -class DbListIterator implements Iterator { - - protected final DbOomQuery query; - protected final boolean entityAwareMode; - protected final ResultSetMapper resultSetMapper; - protected final Class[] types; - protected final boolean closeOnEnd; - - // ---------------------------------------------------------------- ctors - - DbListIterator(final DbOomQuery query, final Class[] types, final boolean closeOnEnd) { - this.query = query; - this.resultSetMapper = query.executeAndBuildResultSetMapper(); - this.entityAwareMode = query.entityAwareMode; - this.types = (types == null ? resultSetMapper.resolveTables() : types); - this.closeOnEnd = closeOnEnd; - } - - DbListIterator(final DbOomQuery query, final Class[] types, final ResultSetMapper resultSetMapper, final boolean closeOnEnd) { - this.query = query; - this.resultSetMapper = resultSetMapper; - this.entityAwareMode = query.entityAwareMode; - this.types = (types == null ? resultSetMapper.resolveTables() : types); - this.closeOnEnd = closeOnEnd; - } - - // ---------------------------------------------------------------- iterate - - protected T previousElement; - protected T newElement; - protected int count; - protected boolean last; - protected Boolean hasNext; - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - - /** - * Returns true
if there is {@link #next() next} parsed object - * available. - */ - @Override - public boolean hasNext() { - if (hasNext == null) { - hasNext = Boolean.valueOf(moveToNext()); - } - return hasNext.booleanValue(); - } - - /** - * Returns next mapped object. - */ - @Override - public T next() { - if (hasNext == null) { - hasNext = Boolean.valueOf(moveToNext()); - } - if (hasNext == false) { - throw new NoSuchElementException(); - } - - if (!entityAwareMode) { - hasNext = null; - return newElement; - } - - count++; - - T result = previousElement; - - previousElement = newElement; - - hasNext = null; - return result; - } - - - /** - * Moves to next element. - */ - private boolean moveToNext() { - if (last) { - // last has been set to true, so no more rows to iterate - close everything - - if (closeOnEnd) { - query.close(); - } else { - query.closeResultSet(resultSetMapper.getResultSet()); - } - - return false; - } - - while (true) { - - if (!resultSetMapper.next()) { - // no more rows, no more parsing, previousElement is the last one to iterate - last = true; - return entityAwareMode; - } - - // parse row - - Object[] objects = resultSetMapper.parseObjects(types); - - Object row = query.resolveRowResults(objects); - - newElement = (T) row; - - if (entityAwareMode) { - - if (count == 0 && previousElement == null) { - previousElement = newElement; - - continue; - } - - if (previousElement != null && newElement != null) { - boolean equals; - - if (newElement.getClass().isArray()) { - equals = Arrays.equals((Object[]) previousElement, (Object[]) newElement); - } else { - equals = previousElement.equals(newElement); - } - - if (equals) { - continue; - } - } - } - - break; - } - - return true; - } - -} diff --git a/jodd-db/src/main/java/jodd/db/oom/DbMetaUtil.java b/jodd-db/src/main/java/jodd/db/oom/DbMetaUtil.java deleted file mode 100644 index 053d750aa..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/DbMetaUtil.java +++ /dev/null @@ -1,189 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom; - -import jodd.db.oom.meta.DbColumn; -import jodd.db.oom.meta.DbId; -import jodd.db.oom.meta.DbMapTo; -import jodd.db.oom.meta.DbTable; -import jodd.db.oom.naming.ColumnNamingStrategy; -import jodd.db.oom.naming.TableNamingStrategy; -import jodd.db.type.SqlType; -import jodd.introspector.PropertyDescriptor; -import jodd.util.StringUtil; - -/** - * Meta-data resolving utils. - */ -public class DbMetaUtil { - - /** - * Resolves table name from a type. If type is annotated, table name - * will be read from annotation value. If this value is empty or if - * type is not annotated, table name will be set to wildcard pattern '*' - * (to match all tables). - */ - public static String resolveTableName(final Class> type, final TableNamingStrategy tableNamingStrategy) { - String tableName = null; - final DbTable dbTable = type.getAnnotation(DbTable.class); - if (dbTable != null) { - tableName = dbTable.value().trim(); - } - if ((tableName == null) || (tableName.length() == 0)) { - tableName = tableNamingStrategy.convertEntityNameToTableName(type); - } else { - if (!tableNamingStrategy.isStrictAnnotationNames()) { - tableName = tableNamingStrategy.applyToTableName(tableName); - } - } - - return quoteIfRequired(tableName, tableNamingStrategy.isAlwaysQuoteNames(), tableNamingStrategy.getQuoteChar()); - } - - /** - * Resolves schema name from a type. Uses default schema name if not specified. - */ - public static String resolveSchemaName(final Class> type, final String defaultSchemaName) { - String schemaName = null; - final DbTable dbTable = type.getAnnotation(DbTable.class); - if (dbTable != null) { - schemaName = dbTable.schema().trim(); - } - if ((schemaName == null) || (schemaName.length() == 0)) { - schemaName = defaultSchemaName; - } - return schemaName; - } - - /** - * Returnstrue
if class is annotated withDbTable
annotation. - */ - public static boolean resolveIsAnnotated(final Class> type) { - final DbTable dbTable = type.getAnnotation(DbTable.class); - return dbTable != null; - } - - /** - * Resolves column descriptor from property. If property is annotated value will be read - * from annotation. If property is not annotated, then property will be ignored - * if entity is annotated. Otherwise, column name is generated from the property name. - */ - public static DbEntityColumnDescriptor resolveColumnDescriptors( - final DbEntityDescriptor dbEntityDescriptor, - final PropertyDescriptor property, - final boolean isAnnotated, - final ColumnNamingStrategy columnNamingStrategy) { - - String columnName = null; - boolean isId = false; - Class extends SqlType> sqlTypeClass = null; - - // read ID annotation - - DbId dbId = null; - - if (property.getFieldDescriptor() != null) { - dbId = property.getFieldDescriptor().getField().getAnnotation(DbId.class); - } - if (dbId == null && property.getReadMethodDescriptor() != null) { - dbId = property.getReadMethodDescriptor().getMethod().getAnnotation(DbId.class); - } - if (dbId == null && property.getWriteMethodDescriptor() != null) { - dbId = property.getWriteMethodDescriptor().getMethod().getAnnotation(DbId.class); - } - - if (dbId != null) { - columnName = dbId.value().trim(); - sqlTypeClass = dbId.sqlType(); - isId = true; - } else { - DbColumn dbColumn = null; - - if (property.getFieldDescriptor() != null) { - dbColumn = property.getFieldDescriptor().getField().getAnnotation(DbColumn.class); - } - if (dbColumn == null && property.getReadMethodDescriptor() != null) { - dbColumn = property.getReadMethodDescriptor().getMethod().getAnnotation(DbColumn.class); - } - if (dbColumn == null && property.getWriteMethodDescriptor() != null) { - dbColumn = property.getWriteMethodDescriptor().getMethod().getAnnotation(DbColumn.class); - } - - if (dbColumn != null) { - columnName = dbColumn.value().trim(); - sqlTypeClass = dbColumn.sqlType(); - } else { - if (isAnnotated) { - return null; - } - } - } - - if (StringUtil.isEmpty(columnName)) { - // default annotation value - columnName = columnNamingStrategy.convertPropertyNameToColumnName(property.getName()); - } else { - if (!columnNamingStrategy.isStrictAnnotationNames()) { - columnName = columnNamingStrategy.applyToColumnName(columnName); - } - } - if (sqlTypeClass == SqlType.class) { - sqlTypeClass = null; - } - - return new DbEntityColumnDescriptor( - dbEntityDescriptor, - quoteIfRequired(columnName, columnNamingStrategy.isAlwaysQuoteNames(), columnNamingStrategy.getQuoteChar()), - property.getName(), - property.getType(), - isId, - sqlTypeClass); - } - - /** - * Resolves mapped types from {@link jodd.db.oom.meta.DbMapTo} annotation. - */ - public static Class[] resolveMappedTypes(final Class type) { - final DbMapTo dbMapTo = (DbMapTo) type.getAnnotation(DbMapTo.class); - if (dbMapTo == null) { - return null; - } - return dbMapTo.value(); - } - - // ---------------------------------------------------------------- privates - - private static String quoteIfRequired(final String name, final boolean alwaysQuoteNames, final char quoteChar) { - if (StringUtil.detectQuoteChar(name) != 0) { - return name; // already quoted - } - if (alwaysQuoteNames && quoteChar != 0) { - return quoteChar + name + quoteChar; - } - return name; - } - -} diff --git a/jodd-db/src/main/java/jodd/db/oom/DbOomConfig.java b/jodd-db/src/main/java/jodd/db/oom/DbOomConfig.java deleted file mode 100644 index e5e93ec5c..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/DbOomConfig.java +++ /dev/null @@ -1,165 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom; - -import jodd.db.oom.naming.ColumnNamingStrategy; -import jodd.db.oom.naming.TableNamingStrategy; - -/** - * DBOOM configuration for names and SQL generation. - */ -public class DbOomConfig { - - /** - * Specifies separator for column aliases that divides table reference and column name. - * Separator should contains of characters that are not used in table names, such as: - * '$' or '__'. - */ - private String columnAliasSeparator = "$"; - /** - * Default column alias type. - */ - private ColumnAliasType defaultColumnAliasType; - /** - * Optional schema name. - */ - private String schemaName; - /** - * Table name strategy. - */ - private TableNamingStrategy tableNames = new TableNamingStrategy(); - /** - * Column name strategy. - */ - private ColumnNamingStrategy columnNames = new ColumnNamingStrategy(); - - /** - * {@code true} if SQL syntax allow usage of table alias in the update query. - */ - private boolean updateAcceptsTableAlias = true; - - /** - * {@code true} if database supports update of the primary key. - */ - private boolean updateablePrimaryKey = true; - - /** - * Defines entity-aware mode, when resulting collections does not have duplicates. - * It make sense to enable it if {@link #cacheEntitiesInResultSet cache} is set. - */ - private boolean entityAwareMode = false; - - /** - * Defines if entities have to be cached in result set. - * When cached, more memory is consumed during the existence of - * {@link jodd.db.oom.mapper.ResultSetMapper}. - */ - private boolean cacheEntitiesInResultSet = false; - - /** - * Specifies how primary keys are generated by database. - */ - protected boolean keysGeneratedByDatabase = true; - - // ---------------------------------------------------------------- r/o - - public TableNamingStrategy getTableNames() { - return tableNames; - } - - public ColumnNamingStrategy getColumnNames() { - return columnNames; - } - - - // ---------------------------------------------------------------- access - - public String getColumnAliasSeparator() { - return columnAliasSeparator; - } - - public void setColumnAliasSeparator(final String separator) { - this.columnAliasSeparator = separator; - } - - - public ColumnAliasType getDefaultColumnAliasType() { - return defaultColumnAliasType; - } - - public void setDefaultColumnAliasType(final ColumnAliasType defaultColumnAliasType) { - this.defaultColumnAliasType = defaultColumnAliasType; - } - - public String getSchemaName() { - return schemaName; - } - - public void setSchemaName(final String schemaName) { - this.schemaName = schemaName; - } - - public boolean isUpdateAcceptsTableAlias() { - return updateAcceptsTableAlias; - } - - public void setUpdateAcceptsTableAlias(final boolean updateAcceptsTableAlias) { - this.updateAcceptsTableAlias = updateAcceptsTableAlias; - } - - public boolean isUpdateablePrimaryKey() { - return updateablePrimaryKey; - } - - public void setUpdateablePrimaryKey(final boolean updateablePrimaryKey) { - this.updateablePrimaryKey = updateablePrimaryKey; - } - - public boolean isEntityAwareMode() { - return entityAwareMode; - } - - public void setEntityAwareMode(final boolean entityAwareMode) { - this.entityAwareMode = entityAwareMode; - } - - public boolean isCacheEntitiesInResultSet() { - return cacheEntitiesInResultSet; - } - - public void setCacheEntitiesInResultSet(final boolean cacheEntitiesInResultSet) { - this.cacheEntitiesInResultSet = cacheEntitiesInResultSet; - } - - public boolean isKeysGeneratedByDatabase() { - return keysGeneratedByDatabase; - } - - public void setKeysGeneratedByDatabase(final boolean keysGeneratedByDatabase) { - this.keysGeneratedByDatabase = keysGeneratedByDatabase; - } - -} diff --git a/jodd-db/src/main/java/jodd/db/oom/DbOomException.java b/jodd-db/src/main/java/jodd/db/oom/DbOomException.java deleted file mode 100644 index 759ce71f8..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/DbOomException.java +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom; - -import jodd.db.DbQuery; -import jodd.db.DbSqlException; - -/** - * DbOom exceptions. - */ -public class DbOomException extends DbSqlException { - - public DbOomException(final Throwable t) { - super(t); - } - - public DbOomException(final String message) { - super(message); - } - - public DbOomException(final DbQuery dbQuery, final String message) { - super(dbQuery, message); - } - - public DbOomException(final String message, final Throwable t) { - super(message, t); - } - - public DbOomException(final DbQuery dbQuery, final String message, final Throwable t) { - super(dbQuery, message, t); - } - -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/oom/DbOomQuery.java b/jodd-db/src/main/java/jodd/db/oom/DbOomQuery.java deleted file mode 100644 index 64f4dbb6b..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/DbOomQuery.java +++ /dev/null @@ -1,563 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom; - -import jodd.bean.BeanUtil; -import jodd.db.DbOom; -import jodd.db.DbQuery; -import jodd.db.DbSession; -import jodd.db.DbUtil; -import jodd.db.oom.mapper.DefaultResultSetMapper; -import jodd.db.oom.mapper.ResultSetMapper; -import jodd.db.oom.sqlgen.ParameterValue; -import jodd.db.type.SqlType; -import jodd.util.CharUtil; -import jodd.util.StringUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.sql.Connection; -import java.sql.DatabaseMetaData; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * A simple ORM extension for {@link DbQuery}. - *- * OOM extension may map results to objects in two ways: - *
- *
- */ -public class DbOomQuery extends DbQuery- auto mode - when result set is mapped to provided types, and
- *- mapped mode - requires explicit mapping definitions.
- *{ - - private static final Logger log = LoggerFactory.getLogger(DbOomQuery.class); - - // ---------------------------------------------------------------- default ctors - - public DbOomQuery(final DbOom dbOom, final Connection conn, final String sqlString) { - super(dbOom, conn, sqlString); - this.sqlgen = null; - init(dbOom); - } - - public static DbOomQuery query(final Connection conn, final String sqlString) { - return new DbOomQuery(DbOom.get(), conn, sqlString); - } - - public DbOomQuery(final DbOom dbOom, final DbSession session, final String sqlString) { - super(dbOom, session, sqlString); - this.sqlgen = null; - init(dbOom); - } - - public static DbOomQuery query(final DbSession session, final String sqlString) { - return new DbOomQuery(DbOom.get(), session, sqlString); - } - - public DbOomQuery(final DbOom dbOom, final String sqlString) { - super(dbOom, sqlString); - this.sqlgen = null; - init(dbOom); - } - - public static DbOomQuery query(final String sqlString) { - return new DbOomQuery(DbOom.get(), sqlString); - } - - // ---------------------------------------------------------------- sqlgen ctors - - protected final DbSqlGenerator sqlgen; - - public DbOomQuery(final DbOom dbOom, final Connection conn, final DbSqlGenerator sqlgen) { - super(dbOom, conn, sqlgen.generateQuery()); - this.sqlgen = sqlgen; - init(dbOom); - } - public static DbOomQuery query(final Connection conn, final DbSqlGenerator sqlgen) { - return new DbOomQuery(DbOom.get(), conn, sqlgen); - } - - public DbOomQuery(final DbOom dbOom, final DbSession session, final DbSqlGenerator sqlgen) { - super(dbOom, session, sqlgen.generateQuery()); - this.sqlgen = sqlgen; - init(dbOom); - } - public static DbOomQuery query(final DbSession session, final DbSqlGenerator sqlgen) { - return new DbOomQuery(DbOom.get(), session, sqlgen); - } - - public DbOomQuery(final DbOom dbOom, final DbSqlGenerator sqlgen) { - super(dbOom, sqlgen.generateQuery()); - this.sqlgen = sqlgen; - init(dbOom); - } - public static DbOomQuery query(final DbSqlGenerator sqlgen) { - return new DbOomQuery(DbOom.get(), sqlgen); - } - - protected void init(final DbOom dbOom) { - this.sqlString = preprocessSql(sqlString); - this.cacheEntities = dbOom.config().isCacheEntitiesInResultSet(); - this.entityAwareMode = dbOom.config().isEntityAwareMode(); - } - - // ---------------------------------------------------------------- initialization - - /** - * Prepares the query after initialization. Besides default work, it checks if sql generator - * is used, and if so, generator hints and query parameters will be used for this query. - * Note regarding hints: since hints can be added manually, generators hints will be ignored - * if there exists some manually set hints. - */ - @Override - protected void prepareQuery() { - super.prepareQuery(); - if (sqlgen == null) { - return; - } - if (hints == null) { - final String[] joinHints = sqlgen.getJoinHints(); - if (joinHints != null) { - withHints(joinHints); - } - } - // insert parameters - final Map parameters = sqlgen.getQueryParameters(); - if (parameters == null) { - return; - } - for (final Map.Entry entry : parameters.entrySet()) { - final String paramName = entry.getKey(); - final ParameterValue param = entry.getValue(); - final DbEntityColumnDescriptor dec = param.getColumnDescriptor(); - if (dec == null) { - setObject(paramName, param.getValue()); - } else { - resolveColumnDbSqlType(connection, dec); - setObject(paramName, param.getValue(), dec.getSqlTypeClass(), dec.getDbSqlType()); - } - } - } - - /** - * Resolves column db sql type and populates it in column descriptor if missing. - */ - protected void resolveColumnDbSqlType(final Connection connection, final DbEntityColumnDescriptor dec) { - if (dec.dbSqlType != SqlType.DB_SQLTYPE_UNKNOWN) { - return; - } - ResultSet rs = null; - final DbEntityDescriptor ded = dec.getDbEntityDescriptor(); - try { - final DatabaseMetaData dmd = connection.getMetaData(); - rs = dmd.getColumns(null, ded.getSchemaName(), ded.getTableName(), dec.getColumnName()); - if (rs.next()) { - dec.dbSqlType = rs.getInt("DATA_TYPE"); - } else { - dec.dbSqlType = SqlType.DB_SQLTYPE_NOT_AVAILABLE; - if (log.isWarnEnabled()) { - log.warn("Column SQL type not available: " + ded.toString() + '.' + dec.getColumnName()); - } - } - } catch (final SQLException sex) { - dec.dbSqlType = SqlType.DB_SQLTYPE_NOT_AVAILABLE; - if (log.isWarnEnabled()) { - log.warn("Column SQL type not resolved: " + ded.toString() + '.' + dec.getColumnName(), sex); - } - } finally { - DbUtil.close(rs); - } - } - - /** - * Pre-process SQL before using it. If string starts with a non-ascii char - * or it has no spaces, it will be loaded from the query map. - */ - protected String preprocessSql(String sqlString) { - // detects callable statement - if (sqlString.charAt(0) == '{') { - return sqlString; - } - - // quickly detect if SQL string is a key - if (!CharUtil.isAlpha(sqlString.charAt(0))) { - sqlString = sqlString.substring(1); - } - else if (sqlString.indexOf(' ') != -1) { - return sqlString; - } - - final String sqlFromMap = dbOom.queryMap().getQuery(sqlString); - - if (sqlFromMap != null) { - sqlString = sqlFromMap.trim(); - } - - return sqlString; - } - - - - // ---------------------------------------------------------------- join hints - - protected JoinHintResolver hintResolver; - - protected String[] hints; - - /** - * Specifies hints for the query. Provided string is - * split on ',' separator. - */ - public DbOomQuery withHints(final String hint) { - this.hints = StringUtil.splitc(hint, ','); - return this; - } - - /** - * Specifies multiple hints for the query. - */ - public DbOomQuery withHints(final String... hints) { - this.hints = hints; - return this; - } - - /** - * Prepares a row (array of rows mapped object) using hints. - * Returns either single object or objects array. - */ - protected Object resolveRowResults(Object[] row) { - if (hintResolver == null) { - hintResolver = new JoinHintResolver(); - } - row = hintResolver.join(row, hints); - return row.length == 1 ? row[0] : row; - } - - // ---------------------------------------------------------------- result set - - protected boolean cacheEntities; - - /** - * Defines if entities should be cached in {@link ResultSetMapper}. - * Overrides default value in {@link DbEntityManager}. - */ - public DbOomQuery cacheEntities(final boolean cacheEntities) { - this.cacheEntities = cacheEntities; - return this; - } - - /** - * Executes the query and returns {@link #createResultSetMapper(java.sql.ResultSet) builded ResultSet mapper}. - */ - protected ResultSetMapper executeAndBuildResultSetMapper() { - final ResultSet resultSet = execute(); - - return createResultSetMapper(resultSet); - } - - /** - * Factory for result sets mapper. - */ - protected ResultSetMapper createResultSetMapper(final ResultSet resultSet) { - final Map columnAliases = sqlgen != null ? sqlgen.getColumnData() : null; - - return new DefaultResultSetMapper(dbOom, resultSet, columnAliases, cacheEntities, this); - } - - // ---------------------------------------------------------------- db list - - protected boolean entityAwareMode; - - /** - * Defines entity-aware mode for entities tracking in result collection. - */ - public DbOomQuery entityAwareMode(final boolean entityAware) { - if (entityAware) { - this.cacheEntities = true; - } - this.entityAwareMode = entityAware; - return this; - } - - // ---------------------------------------------------------------- iterator - - public Iterator iterate(final Class... types) { - return iterate(types, autoClose); - } - public Iterator iterate() { - return iterate(null, autoClose); - } - protected Iterator iterate(final Class[] types, final boolean close) { - return new DbListIterator<>(this, types, close); - } - - // ---------------------------------------------------------------- list - - public List list(final Class... types) { - return list(types, -1, autoClose); - } - public List list() { - return list(null, -1, autoClose); - } - public List list(final int max, final Class... types) { - return list(types, max, autoClose); - } - public List list(final int max) { - return list(null, max, autoClose); - } - /** - * Iterates result set, maps rows to classes and populates resulting array list. - * @param types mapping types - * @param max max number of rows to collect, -1
for all - * @param closetrue
if query is closed at the end, otherwisefalse
. - * @return list of mapped entities or array of entities - */ - @SuppressWarnings({"unchecked"}) - protectedList list(Class[] types, final int max, final boolean close) { - final List result = new ArrayList<>(initialCollectionSize(max)); - - final ResultSetMapper rsm = executeAndBuildResultSetMapper(); - if (types == null) { - types = rsm.resolveTables(); - } - - Object previousElement = null; - - while (rsm.next()) { - final Object[] objects = rsm.parseObjects(types); - final Object row = resolveRowResults(objects); - - final int size = result.size(); - - final T newElement = (T) row; - - if (entityAwareMode && size > 0) { - if (previousElement != null && newElement != null) { - final boolean equals; - - if (newElement.getClass().isArray()) { - equals = Arrays.equals((Object[]) previousElement, (Object[]) newElement); - } else { - equals = previousElement.equals(newElement); - } - - if (equals) { - continue; - } - } - } - - if (size == max) { - break; - } - - result.add(newElement); - previousElement = newElement; - } - - close(rsm, close); - return result; - } - - /** - * Returns initial collections size when max
- * value is provided. - */ - private static int initialCollectionSize(final int max) { - return max > 0 ? max : 10; - } - - - // ---------------------------------------------------------------- set - - publicSet listSet(final Class... types) { - return listSet(types, -1, autoClose); - } - public Set listSet() { - return listSet(null, -1, autoClose); - } - public Set listSet(final int max, final Class... types) { - return listSet(types, max, autoClose); - } - public Set listSet(final int max) { - return listSet(null, max, autoClose); - } - @SuppressWarnings({"unchecked"}) - protected Set listSet(Class[] types, final int max, final boolean close) { - final Set result = new LinkedHashSet<>(initialCollectionSize(max)); - - final ResultSetMapper rsm = executeAndBuildResultSetMapper(); - if (types == null) { - types = rsm.resolveTables(); - } - - Object previousElement = null; - - while (rsm.next()) { - final Object[] objects = rsm.parseObjects(types); - final Object row = resolveRowResults(objects); - - final int size = result.size(); - - final T newElement = (T) row; - - if (entityAwareMode && size > 0) { - if (previousElement != null && newElement != null) { - final boolean equals; - - if (newElement.getClass().isArray()) { - equals = Arrays.equals((Object[]) previousElement, (Object[]) newElement); - } else { - equals = previousElement.equals(newElement); - } - - if (equals) { - continue; - } - } - } - - if (size == max) { - break; - } - - result.add(newElement); - previousElement = newElement; - } - - close(rsm, close); - return result; - } - - // ---------------------------------------------------------------- find - - public T find(final Class... types) { - return find(types, autoClose, null); - } - public T find() { - return find(null, autoClose, null); - } - protected T find(final Class[] types, final boolean close, ResultSet resultSet) { - if (resultSet == null) { - resultSet = execute(); - } - final ResultSetMapper rsm = createResultSetMapper(resultSet); - - final Iterator iterator = new DbListIterator<>(this, types, rsm, false); - - T result = null; - - if (iterator.hasNext()) { - result = iterator.next(); - } - - close(rsm, close); - return result; - } - - // ---------------------------------------------------------------- generated columns - - /** - * Finds generated key column of given type. - */ - public T findGeneratedKey(final Class type) { - return find(new Class[] {type}, false, getGeneratedColumns()); - } - - /** - * Finds generated columns. - */ - public Object findGeneratedColumns(final Class... types) { - return find(types, false, getGeneratedColumns()); - } - - - /** - * Populates entity with generated column values from executed query. - */ - public void populateGeneratedKeys(final Object entity) { - - final String[] generatedColumns = getGeneratedColumnNames(); - if (generatedColumns == null) { - return; - } - final DbEntityDescriptor ded = dbOom.entityManager().lookupType(entity.getClass()); - - // prepare key types - final Class[] keyTypes = new Class[generatedColumns.length]; - final String[] properties = new String[generatedColumns.length]; - for (int i = 0; i < generatedColumns.length; i++) { - final String column = generatedColumns[i]; - final DbEntityColumnDescriptor decd = ded.findByColumnName(column); - if (decd != null) { - keyTypes[i] = decd.getPropertyType(); - properties[i] = decd.getPropertyName(); - } - } - - final Object keyValues = findGeneratedColumns(keyTypes); - if (!keyValues.getClass().isArray()) { - BeanUtil.declared.setProperty(entity, properties[0], keyValues); - } else { - for (int i = 0; i < properties.length; i++) { - BeanUtil.declared.setProperty(entity, properties[i], ((Object[]) keyValues)[i]); - } - } - } - - - // ---------------------------------------------------------------- util - - /** - * {@inheritDoc} - */ - @Override - public DbOomQuery autoClose() { - super.autoClose(); - return this; - } - - /** - * Closes results set or whole query. - */ - protected void close(final ResultSetMapper rsm, final boolean closeQuery) { - if (closeQuery) { - close(); - } else { - closeResultSet(rsm.getResultSet()); - } - } - -} diff --git a/jodd-db/src/main/java/jodd/db/oom/DbSqlGenerator.java b/jodd-db/src/main/java/jodd/db/oom/DbSqlGenerator.java deleted file mode 100644 index e746abc85..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/DbSqlGenerator.java +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom; - -import jodd.db.oom.sqlgen.ParameterValue; - -import java.util.Map; - -/** - * Generates SQL queries. - */ -public interface DbSqlGenerator { - - /** - * Generates SQL query. May be called multiple times. - */ - String generateQuery(); - - /** - * Returns a map of SQL parameters used by generated query. - * Must be invoked only after the {@link #generateQuery()}. - * May be null
- */ - MapgetQueryParameters(); - - /** - * Returns an optional map of table and column names, used by {@link jodd.db.oom.mapper.ResultSetMapper}. - * May be null
. - */ - MapgetColumnData(); - - /** - * Returns join hints. May be null
. - */ - String[] getJoinHints(); - -} diff --git a/jodd-db/src/main/java/jodd/db/oom/JoinHintResolver.java b/jodd-db/src/main/java/jodd/db/oom/JoinHintResolver.java deleted file mode 100644 index ad9c5762a..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/JoinHintResolver.java +++ /dev/null @@ -1,180 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom; - -import jodd.bean.BeanUtil; -import jodd.introspector.ClassDescriptor; -import jodd.introspector.ClassIntrospector; -import jodd.util.ArraysUtil; -import jodd.util.ClassUtil; -import jodd.util.StringUtil; - -import java.lang.reflect.Array; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Joins an array of objects using provided hints. - * If hint is not available, methods returns the very same object array instance. - */ -public class JoinHintResolver { - - public Object[] join(final Object[] data, final String hints) { - if (hints == null) { - return data; - } - return join(data, StringUtil.splitc(hints, ',')); - } - - /** - * Joins entity array using provided string hints. - */ - public Object[] join(final Object[] data, final String[] hints) { - if (hints == null) { - return data; - } - // build context - Mapcontext = new HashMap<>(hints.length); - for (int i = 0; i < hints.length; i++) { - hints[i] = hints[i].trim(); - String hint = hints[i]; - if (hint.indexOf('.') == -1) { - context.put(hint, data[i]); - } - } - - // no joining hints found - if (context.size() == data.length) { - return data; - } - - // joining - Object[] result = new Object[context.size()]; - int count = 0; - for (int i = 0; i < hints.length; i++) { - - String hint = hints[i]; - int ndx = hint.indexOf('.'); - if (ndx != -1) { - String key = hint.substring(0, ndx); - Object value = context.get(key); - if (value == null) { - throw new DbOomException("Hint value missing: " + key); - } - - // don't merge nulls - if (data[i] == null) { - continue; - } - - String hintPropertyName = hint.substring(ndx + 1); - Class hintPropertyType = BeanUtil.pojo.getPropertyType(value, hintPropertyName); - - if (hintPropertyType != null) { - ClassDescriptor cd = ClassIntrospector.get().lookup(hintPropertyType); - - if (cd.isCollection()) { - // add element to collection - try { - Collection collection = BeanUtil.declared.getProperty(value, hintPropertyName); - - if (collection == null) { - collection = (Collection) ClassUtil.newInstance(hintPropertyType); - BeanUtil.declaredSilent.setProperty(value, hintPropertyName, collection); - } - - collection.add(data[i]); - } catch (Exception ex) { - throw new DbOomException(ex); - } - } else if (cd.isArray()) { - // add element to array - try { - Object[] array = BeanUtil.declared.getProperty(value, hintPropertyName); - - if (array == null) { - array = (Object[]) Array.newInstance(hintPropertyType.getComponentType(), 1); - - BeanUtil.declaredSilent.setProperty(value, hintPropertyName, array); - - array[0] = data[i]; - } else { - Object[] newArray = ArraysUtil.append(array, data[i]); - - if (newArray != array) { - BeanUtil.declaredSilent.setProperty(value, hintPropertyName, newArray); - } - } - } catch (Exception ex) { - throw new DbOomException(ex); - } - } else { - // set value - BeanUtil.declaredSilent.setProperty(value, hintPropertyName, data[i]); - } - } - else { - // special case - the property probably contains the collection in the way - - int lastNdx = hintPropertyName.lastIndexOf('.'); - - String name = hintPropertyName.substring(0, lastNdx); - - Object target = resolveValueInSpecialCase(value, name); - - if (target != null) { - String targetSimpleName = hintPropertyName.substring(lastNdx + 1); - - BeanUtil.declaredForcedSilent.setProperty(target, targetSimpleName, data[i]); - } - } - - } else { - result[count] = data[i]; - count++; - } - } - return result; - } - - protected Object resolveValueInSpecialCase(Object value, final String name) { - String[] elements = StringUtil.splitc(name, '.'); - - for (String element : elements) { - value = BeanUtil.declaredSilent.getProperty(value, element); - - if (value instanceof List) { - List list = (List) value; - - value = list.get(list.size() - 1); - } - } - - return value; - } -} diff --git a/jodd-db/src/main/java/jodd/db/oom/NamedValuesHashMap.java b/jodd-db/src/main/java/jodd/db/oom/NamedValuesHashMap.java deleted file mode 100644 index f10f99134..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/NamedValuesHashMap.java +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom; - -import java.util.HashMap; - -/** - * HashMap
withString
keys that are case-insensitive. - */ -public class NamedValuesHashMapextends HashMap { - - @Override - public V put(String key, final V value) { - key = key.toUpperCase(); - return super.put(key, value); - } - - @Override - public V get(Object key) { - key = ((String)key).toUpperCase(); - return super.get(key); - } - -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/oom/dao/GenericDao.java b/jodd-db/src/main/java/jodd/db/oom/dao/GenericDao.java deleted file mode 100644 index 73d0108e2..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/dao/GenericDao.java +++ /dev/null @@ -1,291 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom.dao; - -import jodd.bean.BeanUtil; -import jodd.db.DbOom; -import jodd.db.DbQuery; -import jodd.db.oom.DbEntityDescriptor; -import jodd.db.oom.DbOomException; - -import java.util.List; - -import static jodd.db.oom.DbOomQuery.query; - -/** - * Generic DAO. Contains many convenient wrappers. - */ -public class GenericDao { - - private final DbOom dbOom; - - public GenericDao(final DbOom dbOom) { - this.dbOom = dbOom; - } - - // ---------------------------------------------------------------- store - - /** - * Returns true
if entity is persistent. - */ - protectedboolean isPersistent(final DbEntityDescriptor ded, final E entity) { - final Object key = ded.getIdValue(entity); - - if (key == null) { - return false; - } - if (key instanceof Number) { - final long value = ((Number)key).longValue(); - - if (value == 0) { - return false; - } - } - return true; - } - - /** - * Sets new ID value for entity. - */ - protected void setEntityId(final DbEntityDescriptor ded, final E entity, final ID newIdValue) { - ded.setIdValue(entity, newIdValue); - } - - /** - * Generates next id for given type. - */ - protected ID generateNextId(final DbEntityDescriptor dbEntityDescriptor) { - throw new UnsupportedOperationException("Use Joy"); - } - - /** - * Saves or updates entity. If ID is not null
, entity will be updated. - * Otherwise, entity will be inserted into the database. - */ - publicE store(final E entity) { - final Class type = entity.getClass(); - final DbEntityDescriptor ded = dbOom.entityManager().lookupType(type); - - if (ded == null) { - throw new DbOomException("Not an entity: " + type); - } - if (!isPersistent(ded, entity)) { - final DbQuery q; - if (dbOom.config().isKeysGeneratedByDatabase()) { - q = query(dbOom.entities().insert(entity)); - q.setGeneratedKey(); - q.executeUpdate(); - final Object nextId = q.getGeneratedKey(); - setEntityId(ded, entity, nextId); - } - else { - final Object nextId = generateNextId(ded); - setEntityId(ded, entity, nextId); - q = query(dbOom.entities().insert(entity)); - q.executeUpdate(); - } - q.close(); - } - else { - query(dbOom.entities().updateAll(entity)).autoClose().executeUpdate(); - } - return entity; - } - - /** - * Simply inserts object into the database. - */ - public void save(final Object entity) { - final DbQuery q = query(dbOom.entities().insert(entity)); - q.autoClose().executeUpdate(); - } - - /** - * Inserts bunch of objects into the database. - * @see #save(Object) - */ - public void saveAll(final Iterable entities) { - for (final Object entity: entities) { - save(entity); - } - } - - // ---------------------------------------------------------------- update - - /** - * Updates single entity. - */ - public void update(final Object entity) { - query(dbOom.entities().updateAll(entity)).autoClose().executeUpdate(); - } - - /** - * Updates all entities. - * @see #update(Object) - */ - public void updateAll(final Iterable entities) { - for (final Object entity : entities) { - update(entity); - } - } - - /** - * Updates single property in database and in the bean. - */ - public E updateProperty(final E entity, final String name, final Object newValue) { - query(dbOom.entities().updateColumn(entity, name, newValue)).autoClose().executeUpdate(); - BeanUtil.declared.setProperty(entity, name, newValue); - return entity; - } - - /** - * Updates property in the database by storing the current property value. - */ - public E updateProperty(final E entity, final String name) { - Object value = BeanUtil.declared.getProperty(entity, name); - query(dbOom.entities().updateColumn(entity, name, value)).autoClose().executeUpdate(); - return entity; - } - - // ---------------------------------------------------------------- find - - /** - * Finds single entity by its id. - */ - public E findById(final Class entityType, final ID id) { - return query(dbOom.entities().findById(entityType, id)).autoClose().find(entityType); - } - - /** - * Finds single entity by matching property. - */ - public E findOneByProperty(final Class entityType, final String name, final Object value) { - return query(dbOom.entities().findByColumn(entityType, name, value)).autoClose().find(entityType); - } - - /** - * Finds one entity for given criteria. - */ - @SuppressWarnings({"unchecked"}) - public E findOne(final Object criteria) { - return (E) query(dbOom.entities().find(criteria)).autoClose().find(criteria.getClass()); - } - - /** - * Finds list of entities matching given criteria. - */ - @SuppressWarnings({"unchecked"}) - public List find(final Object criteria) { - return query(dbOom.entities().find(criteria)).autoClose().list(criteria.getClass()); - } - - /** - * Finds list of entities matching given criteria. - */ - public List find(final Class entityType, final Object criteria) { - return query(dbOom.entities().find(entityType, criteria)).autoClose().list(entityType); - } - - // ---------------------------------------------------------------- delete - - /** - * Deleted single entity by its id. - */ - public void deleteById(final Class entityType, final ID id) { - query(dbOom.entities().deleteById(entityType, id)).autoClose().executeUpdate(); - } - - /** - * Delete single object by its id. Resets ID value. - */ - public void deleteById(final Object entity) { - if (entity != null) { - int result = query(dbOom.entities().deleteById(entity)).autoClose().executeUpdate(); - - if (result != 0) { - // now reset the ID value - Class type = entity.getClass(); - DbEntityDescriptor ded = dbOom.entityManager().lookupType(type); - - setEntityId(ded, entity, 0); - } - } - } - - /** - * Deletes all objects by their ids. - */ - public void deleteAllById(final Iterable objects) { - for (final Object entity : objects) { - deleteById(entity); - } - } - - // ---------------------------------------------------------------- count - - /** - * Counts number of all entities. - */ - public long count(final Class entityType) { - return query(dbOom.entities().count(entityType)).autoClose().executeCount(); - } - - - // ---------------------------------------------------------------- increase - - /** - * Increases a property. - */ - public void increaseProperty(final Class entityType, final ID id, final String name, final Number delta) { - query(dbOom.entities().increaseColumn(entityType, id, name, delta, true)).autoClose().executeUpdate(); - } - - /** - * Decreases a property. - */ - public void decreaseProperty(final Class entityType, final ID id, final String name, final Number delta) { - query(dbOom.entities().increaseColumn(entityType, id, name, delta, false)).autoClose().executeUpdate(); - } - - // ---------------------------------------------------------------- related - - /** - * Finds related entity. - */ - public List findRelated(final Class target, final Object source) { - return query(dbOom.entities().findForeign(target, source)).autoClose().list(target); - } - - // ---------------------------------------------------------------- list - - /** - * List all entities. - */ - public List listAll(final Class target) { - return query(dbOom.entities().from(target)).autoClose().list(target); - } - -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/oom/dao/package-info.java b/jodd-db/src/main/java/jodd/db/oom/dao/package-info.java deleted file mode 100644 index 712fa88d2..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/dao/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Generic DAO. - */ -package jodd.db.oom.dao; \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/oom/mapper/BaseResultSetMapper.java b/jodd-db/src/main/java/jodd/db/oom/mapper/BaseResultSetMapper.java deleted file mode 100644 index 3210436da..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/mapper/BaseResultSetMapper.java +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom.mapper; - -import jodd.db.oom.DbOomException; - -import java.sql.ResultSet; -import java.sql.SQLException; - -/** - * Common {@link ResultSetMapper} implementation. - */ -public abstract class BaseResultSetMapper implements ResultSetMapper { - - protected final ResultSet resultSet; - - protected BaseResultSetMapper(final ResultSet resultSet) { - this.resultSet = resultSet; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean next() { - try { - return resultSet.next(); - } catch (SQLException sex) { - throw new DbOomException(sex); - } - } - - /** - * {@inheritDoc} - */ - @Override - public void close() { - try { - resultSet.close(); - } catch (SQLException sex) { - // ignore - } - } - - /** - * {@inheritDoc} - */ - @Override - public ResultSet getResultSet() { - return resultSet; - } - - - /** - * {@inheritDoc} - */ - @Override - public Object parseOneObject(final Class... types) { - return parseObjects(types)[0]; - } - -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/oom/mapper/DefaultResultSetMapper.java b/jodd-db/src/main/java/jodd/db/oom/mapper/DefaultResultSetMapper.java deleted file mode 100644 index cc9fb8d9a..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/mapper/DefaultResultSetMapper.java +++ /dev/null @@ -1,524 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom.mapper; - -import jodd.bean.BeanUtil; -import jodd.db.DbOom; -import jodd.db.oom.ColumnData; -import jodd.db.oom.DbEntityColumnDescriptor; -import jodd.db.oom.DbEntityDescriptor; -import jodd.db.oom.DbEntityManager; -import jodd.db.oom.DbOomException; -import jodd.db.oom.DbOomQuery; -import jodd.db.type.SqlType; -import jodd.db.type.SqlTypeManager; -import jodd.typeconverter.TypeConverterManager; - -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Maps all columns of database result set (RS) row to objects. - * It does it in two steps: preparation (reading table and column names) - * and parsing (parsing one result set row to resulting objects). - * - * Preparation
- * Default mapper reads RS column and table names from RS meta-data and external maps, if provided. - * Since column name is always available in RS meta-data, it may be used to hold table name information. - * Column names may contain table code separator that - * divides column name to table reference and column name. Here, table reference may be either table name or - * table alias. When it is table alias, external alias-to-name map must be provided. - * Hence, this defines the table name, and there is no need to read it from RS meta-data. - *- * When column name doesn't contain a separator, it may be either an actual column name, or a column code. - * For column codes, both table and column name is lookup-ed from external map. If column name is an actual column name, - * table information is read from the RS meta data. Unfortunately, some DBs (such Oracle) doesn't implements - * this simple JDBC feature. Therefore, it must be expected that column table name is not available. - *
- * Table name is also not available for columns which are not directly table columns: - * e.g. some calculations, counts etc. - *
- * Parsing
- * Parser takes types array and tries to populate their instances in best possible way. It assumes that provided - * types list matches selected columns. That is very important, and yet very easy and natural to follow. - * So, parser will try to inject columns value into the one result instance. Now, there are two types of instances: - * simple types (numbers and strings) and entities (pojo objects). Simple types are always mapped to - * one and only one column. Entities will be mapped to all possible columns that can be matched starting from - * current column. So, simple types are not column-hungry, entity types are column-hungry:) - * - *- * A column can be injected in one entities property only once. If one column is already mapped to current result, - * RS mapper will assume that current result is finished with mapping and will proceed to the next one. - * Similarly, if property name is not found for a column, RS mapper will proceed to the next result. - * Therefore, entity types are column precise and hungry;) - all listed columns must be mapped somewhere. - * - *
- * Results that are not used during parsing will be set to
null
. - *- */ -public class DefaultResultSetMapper extends BaseResultSetMapper { - - protected final DbOomQuery dbOomQuery; - protected final boolean cacheEntities; - protected final int totalColumns; // total number of columns - protected final String[] columnNames; // list of all column names - protected final int[] columnDbSqlTypes; // list of all column db types - protected final String[] tableNames; // list of table names for each column, table name may be null - - private final Set
resultColumns; // internal columns per entity cache - private final DbEntityManager dbEntityManager; - - // ---------------------------------------------------------------- ctor - - /** - * Reads ResultSet
meta-data for column and table names. - * @param resultSet JDBC result set - * @param columnAliases alias names for columns, if exist - * @param cacheEntities flag if entities should be cached - * @param dbOomQuery query that created this mapper. - */ - public DefaultResultSetMapper( - final DbOom dbOom, - final ResultSet resultSet, - final MapcolumnAliases, - final boolean cacheEntities, - final DbOomQuery dbOomQuery) { - super(resultSet); - - this.dbEntityManager = dbOom.entityManager(); - this.dbOomQuery = dbOomQuery; - this.cacheEntities = cacheEntities; - - //this.resultColumns = new HashSet (); - try { - ResultSetMetaData rsMetaData = resultSet.getMetaData(); - if (rsMetaData == null) { - throw new DbOomException("No ResultSet meta-data"); - } - - totalColumns = rsMetaData.getColumnCount(); - - this.resultColumns = new HashSet<>(totalColumns); - columnNames = new String[totalColumns]; - columnDbSqlTypes = new int[totalColumns]; - tableNames = new String[totalColumns]; - - for (int i = 0; i < totalColumns; i++) { - String columnName = rsMetaData.getColumnLabel(i + 1); - - if (columnName == null) { - columnName = rsMetaData.getColumnName(i + 1); - } - - String tableName = null; - - // resolve column and table name - int sepNdx = columnName.indexOf(dbOom.config().getColumnAliasSeparator()); - if (sepNdx != -1) { - // column alias exist, result set is ignored and columnAliases contains table data - tableName = columnName.substring(0, sepNdx); - if (columnAliases != null) { - ColumnData columnData = columnAliases.get(tableName); - if (columnData != null) { - tableName = columnData.getTableName(); - } - } - columnName = columnName.substring(sepNdx + 1); - } else { - // column alias does not exist, table name is read from columnAliases and result set (if available) - if (columnAliases != null) { - ColumnData columnData = columnAliases.get(columnName); - if (columnData != null) { - tableName = columnData.getTableName(); - columnName = columnData.getColumnName(); - } - } - if (tableName == null) { - try { - tableName = rsMetaData.getTableName(i + 1); - } catch (SQLException sex) { - // ignore - } - if ((tableName != null) && (tableName.length() == 0)) { - tableName = null; - } - } - } - - columnName = columnName.trim(); - if (columnName.length() == 0) { - columnName = null; - } - - if (columnName != null) { - columnName = columnName.trim(); - columnName = columnName.toUpperCase(); - } - columnNames[i] = columnName; - - if (tableName != null) { - tableName = tableName.trim(); - tableName = tableName.toUpperCase(); - } - tableNames[i] = tableName; - columnDbSqlTypes[i] = rsMetaData.getColumnType(i + 1); - } - } catch (SQLException sex) { - throw new DbOomException(dbOomQuery, "Reading ResultSet meta-data failed", sex); - } - } - - // ---------------------------------------------------------------- delegates - - /** - * {@inheritDoc} - */ - @Override - public Class[] resolveTables() { - List classes = new ArrayList<>(tableNames.length); - String lastTableName = null; - resultColumns.clear(); - - for (int i = 0; i < tableNames.length; i++) { - String tableName = tableNames[i]; - String columnName = columnNames[i]; - - if (tableName == null) { - // maybe JDBC driver does not support it - throw new DbOomException(dbOomQuery, "Table name missing in meta-data"); - } - - if ((!tableName.equals(lastTableName)) || (resultColumns.contains(columnName))) { - resultColumns.clear(); - lastTableName = tableName; - - DbEntityDescriptor ded = dbEntityManager.lookupTableName(tableName); - if (ded == null) { - throw new DbOomException(dbOomQuery, "Table name not registered: " + tableName); - } - - classes.add(ded.getType()); - } - resultColumns.add(columnName); - } - return classes.toArray(new Class[0]); - } - - // ---------------------------------------------------------------- cache - - protected DbEntityDescriptor[] cachedDbEntityDescriptors; - protected Class[] cachedUsedTypes; - protected String[] cachedTypesTableNames; - protected String[][] cachedMappedNames; - - /** - * Resolves {@link jodd.db.oom.DbEntityDescriptor} for all given types, - * so not to repeat every time. - */ - protected DbEntityDescriptor[] resolveDbEntityDescriptors(final Class[] types) { - if (cachedDbEntityDescriptors == null) { - DbEntityDescriptor[] descs = new DbEntityDescriptor[types.length]; - for (int i = 0; i < types.length; i++) { - Class type = types[i]; - if (type != null) { - descs[i] = dbEntityManager.lookupType(type); - } - } - cachedDbEntityDescriptors = descs; - } - return cachedDbEntityDescriptors; - } - - /** - * Creates table names for all specified types. - * Since this is usually done once per result set, these names are cached. - * Type name will be null
for simple names, i.e. for all those - * types that returnsnull
when used by {@link DbEntityManager#lookupType(Class)}. - */ - protected String[] resolveTypesTableNames(final Class[] types) { - if (types != cachedUsedTypes) { - cachedTypesTableNames = createTypesTableNames(types); - cachedUsedTypes = types; - } - return cachedTypesTableNames; - } - - /** - * Resolved mapped type names for each type. - */ - protected String[][] resolveMappedTypesTableNames(final Class[] types) { - if (cachedMappedNames == null) { - String[][] names = new String[types.length][]; - for (int i = 0; i < types.length; i++) { - Class type = types[i]; - if (type != null) { - DbEntityDescriptor ded = cachedDbEntityDescriptors[i]; - if (ded != null) { - Class[] mappedTypes = ded.getMappedTypes(); - if (mappedTypes != null) { - names[i] = createTypesTableNames(mappedTypes); - } - } - } - } - cachedMappedNames = names; - } - return cachedMappedNames; - } - - /** - * Creates table names for given types. - */ - protected String[] createTypesTableNames(final Class[] types) { - String[] names = new String[types.length]; - for (int i = 0; i < types.length; i++) { - if (types[i] == null) { - names[i] = null; - continue; - } - DbEntityDescriptor ded = dbEntityManager.lookupType(types[i]); - if (ded != null) { - String tableName = ded.getTableName(); - tableName = tableName.toUpperCase(); - names[i] = tableName; - } - } - return names; - } - - protected int cachedColumnNdx; - protected Object cachedColumnValue; - - // ---------------------------------------------------------------- parse object - - /** - * Reads column value from result set. Since this method may be called more then once for - * the same column, it caches column values. - */ - @SuppressWarnings({"unchecked"}) - protected Object readColumnValue(final int colNdx, final Class destinationType, final Class extends SqlType> sqlTypeClass, final int columnDbSqlType) { - if (colNdx != cachedColumnNdx) { - try { - SqlType sqlType; - if (sqlTypeClass != null) { - sqlType = SqlTypeManager.get().lookupSqlType(sqlTypeClass); - } else { - sqlType = SqlTypeManager.get().lookup(destinationType); - } - if (sqlType != null) { - cachedColumnValue = sqlType.readValue(resultSet, colNdx + 1, destinationType, columnDbSqlType); - } else { - cachedColumnValue = resultSet.getObject(colNdx + 1); - cachedColumnValue = TypeConverterManager.get().convertType(cachedColumnValue, destinationType); - } - } catch (SQLException sex) { - throw new DbOomException(dbOomQuery, "Invalid value for column #" + (colNdx + 1), sex); - } - cachedColumnNdx = colNdx; - } - return cachedColumnValue; - } - - /** - * {@inheritDoc} - */ - @Override - public Object[] parseObjects(final Class... types) { - resultColumns.clear(); - - int totalTypes = types.length; - Object[] result = new Object[totalTypes]; - boolean[] resultUsage = new boolean[totalTypes]; - DbEntityDescriptor[] dbEntityDescriptors = resolveDbEntityDescriptors(types); - String[] typesTableNames = resolveTypesTableNames(types); - String[][] mappedNames = resolveMappedTypesTableNames(types); - - int currentResult = 0; - cachedColumnNdx = -1; - int colNdx = 0; - while (colNdx < totalColumns) { - - // no more types for mapping? - if (currentResult >= totalTypes) { - break; - } - - // skip columns that doesn't map - Class currentType = types[currentResult]; - if (currentType == null) { - colNdx++; - currentResult++; - resultColumns.clear(); - continue; - } - - String columnName = columnNames[colNdx]; - int columnDbSqlType = columnDbSqlTypes[colNdx]; - String tableName = tableNames[colNdx]; - String resultTableName = typesTableNames[currentResult]; - - if (resultTableName == null) { - // match: simple type - result[currentResult] = readColumnValue(colNdx, currentType, null, columnDbSqlType); - resultUsage[currentResult] = true; - colNdx++; - currentResult++; resultColumns.clear(); - continue; - } - - // match table - boolean tableMatched = false; - - if (tableName == null) { - tableMatched = true; - } else if (resultTableName.equals(tableName)) { - tableMatched = true; - } else { - String[] mapped = mappedNames[currentResult]; - if (mapped != null) { - for (String m : mapped) { - if (m.equals(tableName)) { - tableMatched = true; - break; - } - } - } - } - - if (tableMatched) { - if (!resultColumns.contains(columnName)) { - //DbEntityDescriptor ded = dbEntityManager.lookupType(currentType); - DbEntityDescriptor ded = dbEntityDescriptors[currentResult]; - - DbEntityColumnDescriptor dec = ded.findByColumnName(columnName); - String propertyName = (dec == null ? null : dec.getPropertyName()); - - // check if a property that matches column name exist - if (propertyName != null) { - - // if current entity instance does not exist (i.e. we are at the first column - // of some entity), create the instance and store it - if (result[currentResult] == null) { - result[currentResult] = dbEntityManager.createEntityInstance(currentType); - } -/* - boolean success = value != null ? - BeanUtil.setDeclaredPropertySilent(result[currentResult], propertyName, value) : - BeanUtil.hasDeclaredProperty(result[currentResult], propertyName); -*/ - Class type = BeanUtil.declared.getPropertyType(result[currentResult], propertyName); - if (type != null) { - // match: entity - dec.updateDbSqlType(columnDbSqlType); // updates column db sql type information for the entity!!! - Class extends SqlType> sqlTypeClass = dec.getSqlTypeClass(); - Object value = readColumnValue(colNdx, type, sqlTypeClass, columnDbSqlType); - - if (value != null) { - // inject column value into existing entity - BeanUtil.declared.setProperty(result[currentResult], propertyName, value); - resultUsage[currentResult] = true; - } - colNdx++; - resultColumns.add(columnName); - continue; - } - } - } - } - // go to next type, i.e. result - currentResult++; - resultColumns.clear(); - } - - resultColumns.clear(); - for (int i = 0; i < resultUsage.length; i++) { - if (!resultUsage[i]) { - result[i] = null; - } - } - - if (cacheEntities) { - cacheResultSetEntities(result); - } - - return result; - } - - - // ---------------------------------------------------------------- cache - - protected HashMap