
br.com.objectos.db.SqlConnection Maven / Gradle / Ivy
The newest version!
/*
* Copyright 2014 Objectos, Fábrica de Software LTDA.
*
* 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 br.com.objectos.db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* @author [email protected] (Marcio Endo)
*/
public abstract class SqlConnection implements AutoCloseable {
public abstract Dialect dialect();
public abstract Connection connection();
private final List openStatementList = new ArrayList<>();
SqlConnection() {
}
@Override
public void close() {
Iterator statementIterator = openStatementList.iterator();
while (statementIterator.hasNext()) {
SqlStatement stmt = statementIterator.next();
stmt.close();
statementIterator.remove();
}
try {
connection().close();
} catch (SQLException e) {
}
}
public int executeUpdate(SqlExecutable executable) {
try (Statement stmt = connection().createStatement()) {
String sql = executable.render(dialect().sqlBuilder()).toString();
return stmt.executeUpdate(sql);
} catch (SQLException e) {
throw SqlRuntimeException.wrap(e);
}
}
public SqlStatement prepare(SqlBuilder sql) {
try {
String query = sql.toString();
PreparedStatement statement = connection().prepareStatement(query);
SqlStatement ret = new SqlStatement(statement);
openStatementList.add(ret);
return ret;
} catch (SQLException e) {
throw SqlRuntimeException.wrap(e);
}
}
public SqlStatement prepare(SqlExecutable executable) {
return prepare(executable.render(dialect().sqlBuilder()));
}
public SqlStatement prepareAndGenerateKeys(SqlBuilder sql) {
try {
String query = sql.toString();
PreparedStatement statement = connection().prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
SqlStatement ret = new SqlStatement(statement);
openStatementList.add(ret);
return ret;
} catch (SQLException e) {
throw SqlRuntimeException.wrap(e);
}
}
public SqlStatement prepareAndGenerateKeys(SqlExecutable executable) {
return prepareAndGenerateKeys(executable.render(dialect().sqlBuilder()));
}
void commit() throws SqlException {
try {
connection().commit();
} catch (SQLException e) {
throw SqlException.wrap(e);
}
}
void rollback() throws SqlException {
try {
connection().rollback();
} catch (SQLException e) {
throw SqlException.wrap(e);
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy