@Override public SQLExceptionConverter buildSQLExceptionConverter() { return new SQLExceptionConverter() { @Override public JDBCException convert(SQLException sqlException, String message, String sql) { final String sqlState = JDBCExceptionHelper .extractSqlState(sqlException); if (sqlState != null) { if (SQL_GRAMMAR_CATEGORIES.contains(sqlState)) { return new SQLGrammarException(message, sqlException, sql); } else if (DATA_CATEGORIES.contains(sqlState)) { return new DataException(message, sqlException, sql); } else if (LOCK_ACQUISITION_CATEGORIES.contains(sqlState)) { return new LockAcquisitionException(message, sqlException, sql); } } return null; } }; }
/** * Called after executing a query outside the scope of * a Hibernate or JTA transaction */ public void afterNontransactionalQuery(boolean success) { log.trace( "after autocommit" ); try { // check to see if the connection is in auto-commit // mode (no connection means aggressive connection // release outside a JTA transaction context, so MUST // be autocommit mode) boolean isAutocommit = connectionManager.isAutoCommit(); connectionManager.afterTransaction(); if ( isAutocommit ) { owner.afterTransactionCompletion(success, null); } } catch (SQLException sqle) { throw JDBCExceptionHelper.convert( owner.getFactory().getSQLExceptionConverter(), sqle, "could not inspect JDBC autocommit mode" ); } }
public void executeBatch() throws HibernateException { if (batchUpdate!=null) { try { try { doExecuteBatch(batchUpdate); } finally { closeStatement(batchUpdate); } } catch (SQLException sqle) { throw JDBCExceptionHelper.convert( factory.getSQLExceptionConverter(), sqle, "Could not execute JDBC batch update", batchUpdateSQL ); } finally { batchUpdate=null; batchUpdateSQL=null; } } }
public void closeConnection(Connection conn) throws HibernateException { if ( log.isDebugEnabled() ) { log.debug( "closing JDBC connection" + preparedStatementCountsToString() + resultSetCountsToString() ); } try { if ( !conn.isClosed() ) { JDBCExceptionReporter.logAndClearWarnings(conn); } factory.getConnectionProvider().closeConnection(conn); } catch (SQLException sqle) { throw JDBCExceptionHelper.convert( factory.getSQLExceptionConverter(), sqle, "Cannot close connection" ); } }
/** * Pysically opens a JDBC Connection. * * @throws HibernateException */ private void openConnection() throws HibernateException { if ( connection != null ) { return; } log.debug("opening JDBC connection"); try { connection = factory.getConnectionProvider().getConnection(); } catch (SQLException sqle) { throw JDBCExceptionHelper.convert( factory.getSQLExceptionConverter(), sqle, "Cannot open connection" ); } callback.connectionOpened(); // register synch; stats.connect() }
/** * Physically closes the JDBC Connection. */ private void closeConnection() { if ( log.isDebugEnabled() ) { log.debug( "releasing JDBC connection [" + batcher.openResourceStatsAsString() + "]" ); } try { if ( !connection.isClosed() ) { JDBCExceptionReporter.logAndClearWarnings( connection ); } factory.getConnectionProvider().closeConnection( connection ); connection = null; } catch (SQLException sqle) { throw JDBCExceptionHelper.convert( factory.getSQLExceptionConverter(), sqle, "Cannot release connection" ); } }
/** * Suspend the current transaction and perform work in a new transaction */ public Serializable doWorkInNewTransaction(final SessionImplementor session) throws HibernateException { class Work implements IsolatedWork { Serializable generatedValue; public void doWork(Connection connection) throws HibernateException { String sql = null; try { generatedValue = doWorkInCurrentTransaction( connection, sql ); } catch( SQLException sqle ) { throw JDBCExceptionHelper.convert( session.getFactory().getSQLExceptionConverter(), sqle, "could not get or update next value", sql ); } } } Work work = new Work(); Isolater.doIsolatedWork( work, session ); return work.generatedValue; }
public final Serializable performInsert(String insertSQL, SessionImplementor session, Binder binder) { try { // prepare and execute the insert PreparedStatement insert = prepare( insertSQL, session ); try { binder.bindValues( insert ); return executeAndExtract( insert ); } finally { releaseStatement( insert, session ); } } catch ( SQLException sqle ) { throw JDBCExceptionHelper.convert( session.getFactory().getSQLExceptionConverter(), sqle, "could not insert: " + MessageHelper.infoString( persister ), insertSQL ); } }
/** * Extract the name of the violated constraint from the given SQLException. * * @param sqle The exception that was the result of the constraint violation. * @return The extracted constraint name. */ public String extractConstraintName(SQLException sqle) { String constraintName = null; int errorCode = JDBCExceptionHelper.extractErrorCode(sqle); if ( errorCode == -268 ) { constraintName = extractUsingTemplate( "Unique constraint (", ") violated.", sqle.getMessage() ); } else if ( errorCode == -691 ) { constraintName = extractUsingTemplate( "Missing key in referenced table for referential constraint (", ").", sqle.getMessage() ); } else if ( errorCode == -692 ) { constraintName = extractUsingTemplate( "Key value for constraint (", ") is still being referenced.", sqle.getMessage() ); } if (constraintName != null) { // strip table-owner because Informix always returns constraint names as "<table-owner>.<constraint-name>" int i = constraintName.indexOf('.'); if (i != -1) { constraintName = constraintName.substring(i + 1); } } return constraintName; }
public String extractConstraintName(SQLException sqle) { try { int sqlState = Integer.valueOf( JDBCExceptionHelper.extractSqlState(sqle)).intValue(); switch (sqlState) { // CHECK VIOLATION case 23514: return extractUsingTemplate("violates check constraint \"","\"", sqle.getMessage()); // UNIQUE VIOLATION case 23505: return extractUsingTemplate("violates unique constraint \"","\"", sqle.getMessage()); // FOREIGN KEY VIOLATION case 23503: return extractUsingTemplate("violates foreign key constraint \"","\"", sqle.getMessage()); // NOT NULL VIOLATION case 23502: return extractUsingTemplate("null value in column \"","\" violates not-null constraint", sqle.getMessage()); // TODO: RESTRICT VIOLATION case 23001: return null; // ALL OTHER default: return null; } } catch (NumberFormatException nfe) { return null; } }
public Object next() { if ( !hasNext ) throw new NoSuchElementException("No more results"); try { currentResult = nextResult; postNext(); log.debug("returning current results"); return currentResult; } catch (SQLException sqle) { throw JDBCExceptionHelper.convert( session.getFactory().getSQLExceptionConverter(), sqle, "could not get next iterator result" ); } }
public final void close() throws HibernateException { try { // not absolutely necessary, but does help with aggressive release session.getBatcher().closeQueryStatement( ps, resultSet ); } catch (SQLException sqle) { throw JDBCExceptionHelper.convert( session.getFactory().getSQLExceptionConverter(), sqle, "could not close results" ); } finally { try { session.getPersistenceContext().getLoadContexts().cleanup( resultSet ); } catch( Throwable ignore ) { // ignore this error for now log.trace( "exception trying to cleanup load context : " + ignore.getMessage() ); } } }
/** * Extract the name of the violated constraint from the given SQLException. * * @param sqle The exception that was the result of the constraint violation. * @return The extracted constraint name. */ public String extractConstraintName(SQLException sqle) { String constraintName = null; int errorCode = JDBCExceptionHelper.extractErrorCode( sqle ); if ( errorCode == -8 ) { constraintName = extractUsingTemplate( "Integrity constraint violation ", " table:", sqle.getMessage() ); } else if ( errorCode == -9 ) { constraintName = extractUsingTemplate( "Violation of unique index: ", " in statement [", sqle.getMessage() ); } else if ( errorCode == -104 ) { constraintName = extractUsingTemplate( "Unique constraint violation: ", " in statement [", sqle.getMessage() ); } else if ( errorCode == -177 ) { constraintName = extractUsingTemplate( "Integrity constraint violation - no parent ", " table:", sqle.getMessage() ); } return constraintName; }
public String extractConstraintName(SQLException sqle) { String constraintName = null; int errorCode = JDBCExceptionHelper.extractErrorCode( sqle ); if ( errorCode == -8 ) { constraintName = extractUsingTemplate( "; ", " table: ", sqle.getMessage() ); } else if ( errorCode == -9 ) { constraintName = extractUsingTemplate( "; ", " table: ", sqle.getMessage() ); } else if ( errorCode == -104 ) { constraintName = extractUsingTemplate( "; ", " table: ", sqle.getMessage() ); } else if ( errorCode == -177 ) { constraintName = extractUsingTemplate( "; ", " table: ", sqle.getMessage() ); } return constraintName; }
/** * Called by subclasses that load entities * @param persister only needed for logging */ protected final List loadEntity( final SessionImplementor session, final Object key, final Object index, final Type keyType, final Type indexType, final EntityPersister persister) throws HibernateException { if ( log.isDebugEnabled() ) { log.debug( "loading collection element by index" ); } List result; try { result = doQueryAndInitializeNonLazyCollections( session, new QueryParameters( new Type[] { keyType, indexType }, new Object[] { key, index } ), false ); } catch ( SQLException sqle ) { throw JDBCExceptionHelper.convert( factory.getSQLExceptionConverter(), sqle, "could not collection element by index", getSQLString() ); } log.debug("done entity load"); return result; }
/** * Called by subclasses that initialize collections */ public final void loadCollection( final SessionImplementor session, final Serializable id, final Type type) throws HibernateException { if ( log.isDebugEnabled() ) { log.debug( "loading collection: "+ MessageHelper.collectionInfoString( getCollectionPersisters()[0], id, getFactory() ) ); } Serializable[] ids = new Serializable[]{id}; try { doQueryAndInitializeNonLazyCollections( session, new QueryParameters( new Type[]{type}, ids, ids ), true ); } catch ( SQLException sqle ) { throw JDBCExceptionHelper.convert( factory.getSQLExceptionConverter(), sqle, "could not initialize a collection: " + MessageHelper.collectionInfoString( getCollectionPersisters()[0], id, getFactory() ), getSQLString() ); } log.debug("done loading collection"); }
/** * Called by wrappers that batch initialize collections */ public final void loadCollectionBatch( final SessionImplementor session, final Serializable[] ids, final Type type) throws HibernateException { if ( log.isDebugEnabled() ) { log.debug( "batch loading collection: "+ MessageHelper.collectionInfoString( getCollectionPersisters()[0], ids, getFactory() ) ); } Type[] idTypes = new Type[ids.length]; Arrays.fill( idTypes, type ); try { doQueryAndInitializeNonLazyCollections( session, new QueryParameters( idTypes, ids, ids ), true ); } catch ( SQLException sqle ) { throw JDBCExceptionHelper.convert( factory.getSQLExceptionConverter(), sqle, "could not initialize a collection batch: " + MessageHelper.collectionInfoString( getCollectionPersisters()[0], ids, getFactory() ), getSQLString() ); } log.debug("done batch load"); }
/** * Called by subclasses that batch initialize collections */ protected final void loadCollectionSubselect( final SessionImplementor session, final Serializable[] ids, final Object[] parameterValues, final Type[] parameterTypes, final Map namedParameters, final Type type) throws HibernateException { Type[] idTypes = new Type[ids.length]; Arrays.fill( idTypes, type ); try { doQueryAndInitializeNonLazyCollections( session, new QueryParameters( parameterTypes, parameterValues, namedParameters, ids ), true ); } catch ( SQLException sqle ) { throw JDBCExceptionHelper.convert( factory.getSQLExceptionConverter(), sqle, "could not load collection by subselect: " + MessageHelper.collectionInfoString( getCollectionPersisters()[0], ids, getFactory() ), getSQLString() ); } }
/** * Actually execute a query, ignoring the query cache */ protected List doList(final SessionImplementor session, final QueryParameters queryParameters) throws HibernateException { final boolean stats = getFactory().getStatistics().isStatisticsEnabled(); long startTime = 0; if ( stats ) startTime = System.currentTimeMillis(); List result; try { result = doQueryAndInitializeNonLazyCollections( session, queryParameters, true ); } catch ( SQLException sqle ) { throw JDBCExceptionHelper.convert( factory.getSQLExceptionConverter(), sqle, "could not execute query", getSQLString() ); } if ( stats ) { getFactory().getStatisticsImplementor().queryExecuted( getQueryIdentifier(), result.size(), System.currentTimeMillis() - startTime ); } return result; }
public int getSize(Serializable key, SessionImplementor session) { try { PreparedStatement st = session.getBatcher().prepareSelectStatement(sqlSelectSizeString); try { getKeyType().nullSafeSet(st, key, 1, session); ResultSet rs = st.executeQuery(); try { return rs.next() ? rs.getInt(1) - baseIndex : 0; } finally { rs.close(); } } finally { session.getBatcher().closeStatement( st ); } } catch (SQLException sqle) { throw JDBCExceptionHelper.convert( getFactory().getSQLExceptionConverter(), sqle, "could not retrieve collection size: " + MessageHelper.collectionInfoString( this, key, getFactory() ), sqlSelectSizeString ); } }
private boolean exists(Serializable key, Object indexOrElement, Type indexOrElementType, String sql, SessionImplementor session) { try { PreparedStatement st = session.getBatcher().prepareSelectStatement(sql); try { getKeyType().nullSafeSet(st, key, 1, session); indexOrElementType.nullSafeSet( st, indexOrElement, keyColumnNames.length + 1, session ); ResultSet rs = st.executeQuery(); try { return rs.next(); } finally { rs.close(); } } catch( TransientObjectException e ) { return false; } finally { session.getBatcher().closeStatement( st ); } } catch (SQLException sqle) { throw JDBCExceptionHelper.convert( getFactory().getSQLExceptionConverter(), sqle, "could not check row existence: " + MessageHelper.collectionInfoString( this, key, getFactory() ), sqlSelectSizeString ); } }
public Object getElementByIndex(Serializable key, Object index, SessionImplementor session, Object owner) { try { PreparedStatement st = session.getBatcher().prepareSelectStatement(sqlSelectRowByIndexString); try { getKeyType().nullSafeSet(st, key, 1, session); getIndexType().nullSafeSet( st, incrementIndexByBase(index), keyColumnNames.length + 1, session ); ResultSet rs = st.executeQuery(); try { if ( rs.next() ) { return getElementType().nullSafeGet(rs, elementColumnAliases, session, owner); } else { return null; } } finally { rs.close(); } } finally { session.getBatcher().closeStatement( st ); } } catch (SQLException sqle) { throw JDBCExceptionHelper.convert( getFactory().getSQLExceptionConverter(), sqle, "could not read row: " + MessageHelper.collectionInfoString( this, key, getFactory() ), sqlSelectSizeString ); } }
public Connection openConnection() throws HibernateException { log.debug("opening JDBC connection"); try { return factory.getConnectionProvider().getConnection(); } catch (SQLException sqle) { throw JDBCExceptionHelper.convert( factory.getSQLExceptionConverter(), sqle, "Cannot open connection" ); } }
public void cancelLastQuery() throws HibernateException { try { if (lastQuery!=null) lastQuery.cancel(); } catch (SQLException sqle) { throw JDBCExceptionHelper.convert( factory.getSQLExceptionConverter(), sqle, "Cannot cancel query" ); } }
public int performExecuteUpdate(QueryParameters queryParameters, SessionImplementor session) throws HibernateException { coordinateSharedCacheCleanup( session ); if(queryParameters.isCallable()) { throw new IllegalArgumentException("callable not yet supported for native queries"); } int result = 0; PreparedStatement ps; try { queryParameters.processFilters( this.customQuery.getSQL(), session ); String sql = queryParameters.getFilteredSQL(); ps = session.getBatcher().prepareStatement( sql ); try { int col = 1; col += bindPositionalParameters( ps, queryParameters, col, session ); col += bindNamedParameters( ps, queryParameters .getNamedParameters(), col, session ); result = ps.executeUpdate(); } finally { if ( ps != null ) { session.getBatcher().closeStatement( ps ); } } } catch (SQLException sqle) { throw JDBCExceptionHelper.convert( session.getFactory() .getSQLExceptionConverter(), sqle, "could not execute native bulk manipulation query", this.sourceQuery ); } return result; }
private void getNext( SessionImplementor session ) { log.debug("fetching initial value: " + sql); try { PreparedStatement st = session.getBatcher().prepareSelectStatement(sql); try { ResultSet rs = st.executeQuery(); try { if ( rs.next() ) { next = rs.getLong(1) + 1; if ( rs.wasNull() ) next = 1; } else { next = 1; } sql=null; log.debug("first free id: " + next); } finally { rs.close(); } } finally { session.getBatcher().closeStatement(st); } } catch (SQLException sqle) { throw JDBCExceptionHelper.convert( session.getFactory().getSQLExceptionConverter(), sqle, "could not fetch initial value for increment generator", sql ); } }
public Serializable generate(SessionImplementor session, Object obj) throws HibernateException { final String sql = session.getFactory().getDialect().getSelectGUIDString(); try { PreparedStatement st = session.getBatcher().prepareSelectStatement(sql); try { ResultSet rs = st.executeQuery(); final String result; try { rs.next(); result = rs.getString(1); } finally { rs.close(); } log.debug("GUID identifier generated: " + result); return result; } finally { session.getBatcher().closeStatement(st); } } catch (SQLException sqle) { throw JDBCExceptionHelper.convert( session.getFactory().getSQLExceptionConverter(), sqle, "could not retrieve GUID", sql ); } }
public Serializable generate(SessionImplementor session, Object obj) throws HibernateException { try { PreparedStatement st = session.getBatcher().prepareSelectStatement(sql); try { ResultSet rs = st.executeQuery(); try { rs.next(); Serializable result = IdentifierGeneratorFactory.get( rs, identifierType ); if ( log.isDebugEnabled() ) { log.debug("Sequence identifier generated: " + result); } return result; } finally { rs.close(); } } finally { session.getBatcher().closeStatement(st); } } catch (SQLException sqle) { throw JDBCExceptionHelper.convert( session.getFactory().getSQLExceptionConverter(), sqle, "could not get next sequence value", sql ); } }
/** * Extract the name of the violated constraint from the given SQLException. * * @param sqle The exception that was the result of the constraint violation. * @return The extracted constraint name. */ public String extractConstraintName(SQLException sqle) { int errorCode = JDBCExceptionHelper.extractErrorCode(sqle); if ( errorCode == 1 || errorCode == 2291 || errorCode == 2292 ) { return extractUsingTemplate( "constraint (", ") violated", sqle.getMessage() ); } else if ( errorCode == 1400 ) { // simple nullability constraint return null; } else { return null; } }