org.hibernate.JDBCException Java Examples

The following examples show how to use org.hibernate.JDBCException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CacheSQLExceptionConversionDelegate.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Convert the given SQLException into Hibernate's JDBCException hierarchy.
 *
 * @param sqlException The SQLException to be converted.
 * @param message	  An optional error message.
 * @param sql		  Optionally, the sql being performed when the exception occurred.
 * @return The resulting JDBCException; returns null if it could not be converted.
 */
@Override
public JDBCException convert(SQLException sqlException, String message, String sql) {
	String sqlStateClassCode = JdbcExceptionHelper.extractSqlStateClassCode( sqlException );
	if ( sqlStateClassCode != null ) {
		Integer errorCode = JdbcExceptionHelper.extractErrorCode( sqlException );
		if ( INTEGRITY_VIOLATION_CATEGORIES.contains( errorCode ) ) {
			String constraintName =
					getConversionContext()
							.getViolatedConstraintNameExtracter()
							.extractConstraintName( sqlException );
			return new ConstraintViolationException( message, sqlException, sql, constraintName );
		}
		else if ( DATA_CATEGORIES.contains( sqlStateClassCode ) ) {
			return new DataException( message, sqlException, sql );
		}
	}
	return null; // allow other delegates the chance to look
}
 
Example #2
Source File: ReactiveLoader.java    From hibernate-reactive with GNU Lesser General Public License v2.1 6 votes vote down vote up
default CompletionStage<List<Object>> reactiveProcessResultSet(
		ResultSet rs,
		QueryParameters queryParameters,
		SharedSessionContractImplementor session,
		boolean returnProxies,
		ResultTransformer forcedResultTransformer,
		List<AfterLoadAction> afterLoadActions) {
	try {
		return getReactiveResultSetProcessor()
				.reactiveExtractResults(
						rs,
						session,
						queryParameters,
						null,
						returnProxies,
						queryParameters.isReadOnly( session ),
						forcedResultTransformer,
						afterLoadActions
				);
	}
	catch (SQLException sqle) {
		//don't log or convert it - just pass it on to the caller
		throw new JDBCException( "could not load batch", sqle );
	}
}
 
Example #3
Source File: GemFireXDDialect.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public SQLExceptionConversionDelegate buildSQLExceptionConversionDelegate() {
        return new SQLExceptionConversionDelegate() {
                @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;
                }
        };
}
 
Example #4
Source File: SchemaExport.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void create(boolean script, boolean export, Writer fileOutput, Statement statement)
		throws IOException {
	for ( int j = 0; j < createSQL.length; j++ ) {
		try {
			execute( script, export, fileOutput, statement, createSQL[j] );
		}
		catch ( SQLException e ) {
			if ( haltOnError ) {
				throw new JDBCException( "Error during DDL export", e );
			}
			exceptions.add( e );
			log.error( "Unsuccessful: " + createSQL[j] );
			log.error( e.getMessage() );
		}
	}
}
 
Example #5
Source File: ResultCheckStyleTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void testUpdateFailureWithExceptionChecking() {
	Session s = openSession();
	s.beginTransaction();
	ExceptionCheckingEntity e = new ExceptionCheckingEntity();
	e.setId( new Long( 1 ) );
	e.setName( "dummy" );
	s.update( e );
	try {
		s.flush();
		fail( "expection flush failure!" );
	}
	catch( JDBCException ex ) {
		// these should specifically be JDBCExceptions...
	}
	s.clear();
	s.getTransaction().commit();
	s.close();
}
 
Example #6
Source File: GemFireXDDialect.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
@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;
    }
  };
}
 
Example #7
Source File: SQLiteDialect.java    From yeti with MIT License 6 votes vote down vote up
@Override
public SQLExceptionConverter buildSQLExceptionConverter() {
    return new SQLExceptionConverter() {
        @Override
        public JDBCException convert(SQLException sqlException, String message, String sql) {
            final int errorCode = sqlException.getErrorCode();
            if (errorCode == SQLITE_CONSTRAINT) {
                final String constraintName = EXTRACTER.extractConstraintName(sqlException);
                return new ConstraintViolationException(message, sqlException, sql, constraintName);
            } else if (errorCode == SQLITE_TOOBIG || errorCode == SQLITE_MISMATCH) {
                return new DataException(message, sqlException, sql);
            } else if (errorCode == SQLITE_BUSY || errorCode == SQLITE_LOCKED) {
                return new LockAcquisitionException(message, sqlException, sql);
            } else if ((errorCode >= SQLITE_IOERR && errorCode <= SQLITE_PROTOCOL) || errorCode == SQLITE_NOTADB) {
                return new JDBCConnectionException(message, sqlException, sql);
            }
            return new GenericJDBCException(message, sqlException, sql);
        }
    };
}
 
Example #8
Source File: PostgreSQL81Dialect.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public SQLExceptionConversionDelegate buildSQLExceptionConversionDelegate() {
	return new SQLExceptionConversionDelegate() {
		@Override
		public JDBCException convert(SQLException sqlException, String message, String sql) {
			final String sqlState = JdbcExceptionHelper.extractSqlState( sqlException );

			if ( "40P01".equals( sqlState ) ) {
				// DEADLOCK DETECTED
				return new LockAcquisitionException( message, sqlException, sql );
			}

			if ( "55P03".equals( sqlState ) ) {
				// LOCK NOT AVAILABLE
				return new PessimisticLockException( message, sqlException, sql );
			}

			// returning null allows other delegates to operate
			return null;
		}
	};
}
 
Example #9
Source File: SQLServer2005Dialect.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public SQLExceptionConversionDelegate buildSQLExceptionConversionDelegate() {
	return new SQLExceptionConversionDelegate() {
		@Override
		public JDBCException convert(SQLException sqlException, String message, String sql) {
			final String sqlState = JdbcExceptionHelper.extractSqlState( sqlException );
			final int errorCode = JdbcExceptionHelper.extractErrorCode( sqlException );
			if ( "HY008".equals( sqlState ) ) {
				throw new QueryTimeoutException( message, sqlException, sql );
			}
			if (1222 == errorCode ) {
				throw new LockTimeoutException( message, sqlException, sql );
			}
			return null;
		}
	};
}
 
Example #10
Source File: CacheSQLStateConverter.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Convert the given SQLException into Hibernate's JDBCException hierarchy.
 *
 * @param sqlException The SQLException to be converted.
 * @param message	  An optional error message.
 * @param sql		  Optionally, the sql being performed when the exception occurred.
 * @return The resulting JDBCException.
 */
public JDBCException convert(SQLException sqlException, String message, String sql) {
	String sqlStateClassCode = JDBCExceptionHelper.extractSqlStateClassCode( sqlException );
	Integer errorCode = new Integer( JDBCExceptionHelper.extractErrorCode( sqlException ) );
	if ( sqlStateClassCode != null ) {
		if ( SQL_GRAMMAR_CATEGORIES.contains( sqlStateClassCode ) ) {
			return new SQLGrammarException( message, sqlException, sql );
		}
		else if ( INTEGRITY_VIOLATION_CATEGORIES.contains( errorCode ) ) {
			String constraintName = extracter.extractConstraintName( sqlException );
			return new ConstraintViolationException( message, sqlException, sql, constraintName );
		}
		else if ( CONNECTION_CATEGORIES.contains( sqlStateClassCode ) ) {
			return new JDBCConnectionException( message, sqlException, sql );
		}
		else if ( DATA_CATEGORIES.contains( sqlStateClassCode ) ) {
			return new DataException( message, sqlException, sql );
		}
	}
	return handledNonSpecificException( sqlException, message, sql );
}
 
Example #11
Source File: SybaseASE157Dialect.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public SQLExceptionConversionDelegate buildSQLExceptionConversionDelegate() {
	return new SQLExceptionConversionDelegate() {
		@Override
		public JDBCException convert(SQLException sqlException, String message, String sql) {
			final String sqlState = JdbcExceptionHelper.extractSqlState( sqlException );
			final int errorCode = JdbcExceptionHelper.extractErrorCode( sqlException );
			if("JZ0TO".equals( sqlState ) || "JZ006".equals( sqlState )){
				throw new LockTimeoutException( message, sqlException, sql );
			}
			if ( 515 == errorCode && "ZZZZZ".equals( sqlState ) ) {
				// Attempt to insert NULL value into column; column does not allow nulls.
				final String constraintName = getViolatedConstraintNameExtracter().extractConstraintName( sqlException );
				return new ConstraintViolationException( message, sqlException, sql, constraintName );
			}
			return null;
		}
	};
}
 
Example #12
Source File: CustomInsertSQLWithIdentityColumnTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void testBadInsertionFails() {
	Session session = openSession();
	session.beginTransaction();
	Organization org = new Organization( "hola!" );
	try {
		session.save( org );
		session.delete( org );
		fail( "expecting bad custom insert statement to fail" );
	}
	catch( JDBCException e ) {
		// expected failure
	}

	session.getTransaction().rollback();
	session.close();
}
 
Example #13
Source File: GemFireXDDialect.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
@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;
    }
  };
}
 
Example #14
Source File: GemFireXDDialect.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
@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;
                }
        };
}
 
Example #15
Source File: ReactiveAbstractEntityPersister.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
default Object[] processSnapshot(SharedSessionContractImplementor session, ResultSet resultSet) {
	try {
		if ( resultSet.next() ) {
			//return the "hydrated" state (ie. associations are not resolved)
			Type[] types = getPropertyTypes();
			Object[] values = new Object[types.length];
			boolean[] includeProperty = getPropertyUpdateability();
			for ( int i = 0; i < types.length; i++ ) {
				if ( includeProperty[i] ) {
					values[i] = types[i].hydrate(
							resultSet,
							getPropertyAliases( "", i ),
							session,
							null
					); //null owner ok??
				}
			}
			return values;
		}
		else {
			//no corresponding row: transient!
			return null;
		}
	}
	catch (SQLException e) {
		//can't actually occur!
		throw new JDBCException( "error while binding parameters", e );
	}
}
 
Example #16
Source File: SQLStateConverter.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Convert the given SQLException into Hibernate's JDBCException hierarchy.
 *
 * @param sqlException The SQLException to be converted.
 * @param message      An optional error message.
 * @param sql          Optionally, the sql being performed when the exception occurred.
 * @return The resulting JDBCException.
 */
public JDBCException convert(SQLException sqlException, String message, String sql) {
	String sqlState = JDBCExceptionHelper.extractSqlState( sqlException );

	if ( sqlState != null ) {
		String sqlStateClassCode = JDBCExceptionHelper.determineSqlStateClassCode( sqlState );

		if ( sqlStateClassCode != null ) {
			if ( SQL_GRAMMAR_CATEGORIES.contains( sqlStateClassCode ) ) {
				return new SQLGrammarException( message, sqlException, sql );
			}
			else if ( INTEGRITY_VIOLATION_CATEGORIES.contains( sqlStateClassCode ) ) {
				String constraintName = extracter.extractConstraintName( sqlException );
				return new ConstraintViolationException( message, sqlException, sql, constraintName );
			}
			else if ( CONNECTION_CATEGORIES.contains( sqlStateClassCode ) ) {
				return new JDBCConnectionException( message, sqlException, sql );
			}
			else if ( DATA_CATEGORIES.contains( sqlStateClassCode ) ) {
				return new DataException( message, sqlException, sql );
			}
		}

		if ( "40001".equals( sqlState ) ) {
			return new LockAcquisitionException( message, sqlException, sql );
		}

		if ( "61000".equals( sqlState ) ) {
			// oracle sql-state code for deadlock
			return new LockAcquisitionException( message, sqlException, sql );
		}
	}

	return handledNonSpecificException( sqlException, message, sql );
}
 
Example #17
Source File: DB2Dialect.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public SQLExceptionConversionDelegate buildSQLExceptionConversionDelegate() {
	return new SQLExceptionConversionDelegate() {
		@Override
		public JDBCException convert(SQLException sqlException, String message, String sql) {
			final String sqlState = JdbcExceptionHelper.extractSqlState( sqlException );
			final int errorCode = JdbcExceptionHelper.extractErrorCode( sqlException );

			if( -952 == errorCode && "57014".equals( sqlState )){
				throw new LockTimeoutException( message, sqlException, sql );
			}
			return null;
		}
	};
}
 
Example #18
Source File: IteratorImpl.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void close() throws JDBCException {
	if (ps!=null) {
		try {
			log.debug("closing iterator");
			nextResult = null;
			session.getBatcher().closeQueryStatement(ps, rs);
			ps = null;
			rs = null;
			hasNext = false;
		}
		catch (SQLException e) {
			log.info( "Unable to close iterator", e );
			throw JDBCExceptionHelper.convert(
			        session.getFactory().getSQLExceptionConverter(),
			        e,
			        "Unable to close iterator"
				);
		}
		finally {
			try {
				session.getPersistenceContext().getLoadContexts().cleanup( rs );
			}
			catch( Throwable ignore ) {
				// ignore this error for now
				log.trace( "exception trying to cleanup load context : " + ignore.getMessage() );
			}
		}
	}
}
 
Example #19
Source File: ContextualLobCreator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public NClob createNClob(String string) {
	try {
		final NClob nclob = createNClob();
		nclob.setString( 1, string );
		return nclob;
	}
	catch ( SQLException e ) {
		throw new JDBCException( "Unable to set NCLOB string after creation", e );
	}
}
 
Example #20
Source File: BasicConnectionCreator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected JDBCException convertSqlException(String message, SQLException e) {
	// if JdbcServices#getSqlExceptionHelper is available, use it...
	final JdbcServices jdbcServices = serviceRegistry.getService( JdbcServices.class );
	if ( jdbcServices != null && jdbcServices.getSqlExceptionHelper() != null ) {
		return jdbcServices.getSqlExceptionHelper().convert( e, message, null );
	}

	// likely we are still in the process of initializing the ServiceRegistry, so use the simplified
	// SQLException conversion
	return simpleConverterAccess.getValue().convert( e, message, null );
}
 
Example #21
Source File: SQLExceptionTypeDelegate.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public JDBCException convert(SQLException sqlException, String message, String sql) {
	if ( SQLClientInfoException.class.isInstance( sqlException )
			|| SQLInvalidAuthorizationSpecException.class.isInstance( sqlException )
			|| SQLNonTransientConnectionException.class.isInstance( sqlException )
			|| SQLTransientConnectionException.class.isInstance( sqlException ) ) {
		return new JDBCConnectionException( message, sqlException, sql );
	}
	else if ( DataTruncation.class.isInstance( sqlException ) ||
			SQLDataException.class.isInstance( sqlException ) ) {
		throw new DataException( message, sqlException, sql );
	}
	else if ( SQLIntegrityConstraintViolationException.class.isInstance( sqlException ) ) {
		return new ConstraintViolationException(
				message,
				sqlException,
				sql,
				getConversionContext().getViolatedConstraintNameExtracter().extractConstraintName( sqlException )
		);
	}
	else if ( SQLSyntaxErrorException.class.isInstance( sqlException ) ) {
		return new SQLGrammarException( message, sqlException, sql );
	}
	else if ( SQLTimeoutException.class.isInstance( sqlException ) ) {
		return new QueryTimeoutException( message, sqlException, sql );
	}
	else if ( SQLTransactionRollbackException.class.isInstance( sqlException ) ) {
		// Not 100% sure this is completely accurate.  The JavaDocs for SQLTransactionRollbackException state that
		// it indicates sql states starting with '40' and that those usually indicate that:
		//		<quote>
		//			the current statement was automatically rolled back by the database because of deadlock or
		// 			other transaction serialization failures.
		//		</quote>
		return new LockAcquisitionException( message, sqlException, sql );
	}

	return null; // allow other delegates the chance to look
}
 
Example #22
Source File: StandardSQLExceptionConverter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public JDBCException convert(SQLException sqlException, String message, String sql) {
	for ( SQLExceptionConversionDelegate delegate : delegates ) {
		final JDBCException jdbcException = delegate.convert( sqlException, message, sql );
		if ( jdbcException != null ) {
			return jdbcException;
		}
	}
	return new GenericJDBCException( message, sqlException, sql );
}
 
Example #23
Source File: HibernateExceptionTranslator.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Convert the given HibernateException to an appropriate exception from the
 * {@code org.springframework.dao} hierarchy.
 * <p>Will automatically apply a specified SQLExceptionTranslator to a
 * Hibernate JDBCException, otherwise rely on Hibernate's default translation.
 * @param ex the HibernateException that occurred
 * @return a corresponding DataAccessException
 * @see SessionFactoryUtils#convertHibernateAccessException
 */
protected DataAccessException convertHibernateAccessException(HibernateException ex) {
	if (this.jdbcExceptionTranslator != null && ex instanceof JDBCException) {
		JDBCException jdbcEx = (JDBCException) ex;
		DataAccessException dae = this.jdbcExceptionTranslator.translate(
				"Hibernate operation: " + jdbcEx.getMessage(), jdbcEx.getSQL(), jdbcEx.getSQLException());
		if (dae != null) {
			throw dae;
		}
	}
	return SessionFactoryUtils.convertHibernateAccessException(ex);
}
 
Example #24
Source File: ContextualLobCreator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Blob createBlob(byte[] bytes) {
	try {
		final Blob blob = createBlob();
		blob.setBytes( 1, bytes );
		return blob;
	}
	catch ( SQLException e ) {
		throw new JDBCException( "Unable to set BLOB bytes after creation", e );
	}
}
 
Example #25
Source File: GemFireXDDialect.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
@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;
                }
        };
}
 
Example #26
Source File: HibernateExceptionTranslator.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Convert the given HibernateException to an appropriate exception from the
 * {@code org.springframework.dao} hierarchy.
 * <p>Will automatically apply a specified SQLExceptionTranslator to a
 * Hibernate JDBCException, otherwise rely on Hibernate's default translation.
 * @param ex the HibernateException that occurred
 * @return a corresponding DataAccessException
 * @see SessionFactoryUtils#convertHibernateAccessException
 */
protected DataAccessException convertHibernateAccessException(HibernateException ex) {
	if (this.jdbcExceptionTranslator != null && ex instanceof JDBCException) {
		JDBCException jdbcEx = (JDBCException) ex;
		DataAccessException dae = this.jdbcExceptionTranslator.translate(
				"Hibernate operation: " + jdbcEx.getMessage(), jdbcEx.getSQL(), jdbcEx.getSQLException());
		if (dae != null) {
			throw dae;
		}
	}
	return SessionFactoryUtils.convertHibernateAccessException(ex);
}
 
Example #27
Source File: SQLExceptionConverterFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Builds a minimal converter.  The instance returned here just always converts to
 * {@link org.hibernate.exception.GenericJDBCException}.
 *
 * @return The minimal converter.
 */
public static SQLExceptionConverter buildMinimalSQLExceptionConverter() {
	return new SQLExceptionConverter() {
		public JDBCException convert(SQLException sqlException, String message, String sql) {
			return new GenericJDBCException( message, sqlException, sql );
		}
	};
}
 
Example #28
Source File: AbstractIdsBulkIdHandler.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
protected JDBCException convert(
		SQLException e,
		String message,
		String sql) {
	throw factory().getServiceRegistry().getService( JdbcServices.class ).getSqlExceptionHelper().convert( e, message, sql );
}
 
Example #29
Source File: HibernateJdbcException.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
/**
 * Return the underlying SQLException.
 */
public SQLException getSQLException() {
	return ((JDBCException) getCause()).getSQLException();
}
 
Example #30
Source File: SQLExceptionConversionTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void testIntegrityViolation() throws Exception {
	if ( getDialect() instanceof MySQLMyISAMDialect ) {
		reportSkip( "MySQL (ISAM) does not support FK violation checking", "exception conversion" );
		return;
	}
	
	SQLExceptionConverter converter = getDialect().buildSQLExceptionConverter();

	Session session = openSession();
	session.beginTransaction();
	Connection connection = session.connection();

	// Attempt to insert some bad values into the T_MEMBERSHIP table that should
	// result in a constraint violation
	PreparedStatement ps = null;
	try {
		ps = connection.prepareStatement("INSERT INTO T_MEMBERSHIP (user_id, group_id) VALUES (?, ?)");
		ps.setLong(1, 52134241);    // Non-existent user_id
		ps.setLong(2, 5342);        // Non-existent group_id
		ps.executeUpdate();

		fail("INSERT should have failed");
	}
	catch(SQLException sqle) {
		JDBCExceptionReporter.logExceptions(sqle, "Just output!!!!");
		JDBCException jdbcException = converter.convert(sqle, null, null);
		assertEquals( "Bad conversion [" + sqle.getMessage() + "]", ConstraintViolationException.class , jdbcException.getClass() );
		ConstraintViolationException ex = (ConstraintViolationException) jdbcException;
		System.out.println("Violated constraint name: " + ex.getConstraintName());
	}
	finally {
		if ( ps != null ) {
			try {
				ps.close();
			}
			catch( Throwable ignore ) {
				// ignore...
			}
		}
	}

	session.getTransaction().rollback();
	session.close();
}