
scriptella.jdbc.StatementCache Maven / Gradle / Ivy
The newest version!
/*
* Copyright 2006-2012 The Scriptella Project Team.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package scriptella.jdbc;
import scriptella.util.IOUtils;
import scriptella.util.LRUMap;
import java.io.Closeable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Map;
import static scriptella.util.CollectionUtils.isEmpty;
/**
* Statements cache for {@link JdbcConnection}.
* TODO Extract statement handling policy interface and provide 2 implementations for normal and batched mode. (+1 for testing)
* TODO Use wrapper class for Jdbc ConnectionParameters to store typesafe parameters and overridable factories
*
* @author Fyodor Kupolov
* @version 1.0
*/
class StatementCache implements Closeable {
private Map map;
private final Connection connection;
private final JdbcTypesConverter converter;
private int batchSize;
private StatementWrapper.Batched sharedBatchedStatement; //see getter for description
private int fetchSize;
/**
* Creates a statement cache for specified connection.
*
* @param connection connection to create cache for.
* @param size cache size, 0 or negative means disable cache.
* @param batchSize size of prepared statements batch.
* @param fetchSize see {@link java.sql.Statement#setFetchSize(int)}
*/
public StatementCache(Connection connection, final int size, final int batchSize, final int fetchSize) {
this.connection = connection;
this.batchSize = batchSize;
this.converter = new JdbcTypesConverter();
this.fetchSize = fetchSize;
if (size > 0) { //if cache is enabled
map = new CacheMap(size);
}
}
/**
* Prepares a statement.
* The sql is used as a key to lookup a {@link StatementWrapper},
* if cache miss the statement is created and put to cache.
*
* @param sql statement SQL.
* @param params parameters for SQL.
* @return a wrapper for specified SQL.
* @throws SQLException if DB reports an error
* @see StatementWrapper
*/
public StatementWrapper> prepare(final String sql, final List
© 2015 - 2025 Weber Informatics LLC | Privacy Policy