Search in sources :

Example 66 with HibernateException

use of org.hibernate.HibernateException in project hibernate-orm by hibernate.

the class AbstractEntityPersister method getIdByUniqueKey.

@Override
public Serializable getIdByUniqueKey(Serializable key, String uniquePropertyName, SharedSessionContractImplementor session) throws HibernateException {
    if (LOG.isTraceEnabled()) {
        LOG.tracef("resolving unique key [%s] to identifier for entity [%s]", key, getEntityName());
    }
    int propertyIndex = getSubclassPropertyIndex(uniquePropertyName);
    if (propertyIndex < 0) {
        throw new HibernateException("Could not determine Type for property [" + uniquePropertyName + "] on entity [" + getEntityName() + "]");
    }
    Type propertyType = getSubclassPropertyType(propertyIndex);
    try {
        PreparedStatement ps = session.getJdbcCoordinator().getStatementPreparer().prepareStatement(generateIdByUniqueKeySelectString(uniquePropertyName));
        try {
            propertyType.nullSafeSet(ps, key, 1, session);
            ResultSet rs = session.getJdbcCoordinator().getResultSetReturn().extract(ps);
            try {
                //if there is no resulting row, return null
                if (!rs.next()) {
                    return null;
                }
                return (Serializable) getIdentifierType().nullSafeGet(rs, getIdentifierAliases(), session, null);
            } finally {
                session.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release(rs, ps);
            }
        } finally {
            session.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release(ps);
            session.getJdbcCoordinator().afterStatementExecution();
        }
    } catch (SQLException e) {
        throw session.getJdbcServices().getSqlExceptionHelper().convert(e, String.format("could not resolve unique property [%s] to identifier for entity [%s]", uniquePropertyName, getEntityName()), getSQLSnapshotSelectString());
    }
}
Also used : AssociationType(org.hibernate.type.AssociationType) JoinType(org.hibernate.sql.JoinType) CollectionType(org.hibernate.type.CollectionType) EntityType(org.hibernate.type.EntityType) ComponentType(org.hibernate.type.ComponentType) CompositeType(org.hibernate.type.CompositeType) VersionType(org.hibernate.type.VersionType) Type(org.hibernate.type.Type) Serializable(java.io.Serializable) HibernateException(org.hibernate.HibernateException) SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement)

Example 67 with HibernateException

use of org.hibernate.HibernateException in project hibernate-orm by hibernate.

the class NamedQueryRepository method checkNamedQueries.

public Map<String, HibernateException> checkNamedQueries(QueryPlanCache queryPlanCache) {
    Map<String, HibernateException> errors = new HashMap<String, HibernateException>();
    // Check named HQL queries
    log.debugf("Checking %s named HQL queries", namedQueryDefinitionMap.size());
    for (NamedQueryDefinition namedQueryDefinition : namedQueryDefinitionMap.values()) {
        // this will throw an error if there's something wrong.
        try {
            log.debugf("Checking named query: %s", namedQueryDefinition.getName());
            //TODO: BUG! this currently fails for named queries for non-POJO entities
            queryPlanCache.getHQLQueryPlan(namedQueryDefinition.getQueryString(), false, Collections.EMPTY_MAP);
        } catch (HibernateException e) {
            errors.put(namedQueryDefinition.getName(), e);
        }
    }
    // Check native-sql queries
    log.debugf("Checking %s named SQL queries", namedSqlQueryDefinitionMap.size());
    for (NamedSQLQueryDefinition namedSQLQueryDefinition : namedSqlQueryDefinitionMap.values()) {
        // this will throw an error if there's something wrong.
        try {
            log.debugf("Checking named SQL query: %s", namedSQLQueryDefinition.getName());
            // TODO : would be really nice to cache the spec on the query-def so as to not have to re-calc the hash;
            // currently not doable though because of the resultset-ref stuff...
            NativeSQLQuerySpecification spec;
            if (namedSQLQueryDefinition.getResultSetRef() != null) {
                ResultSetMappingDefinition definition = getResultSetMappingDefinition(namedSQLQueryDefinition.getResultSetRef());
                if (definition == null) {
                    throw new MappingException("Unable to find resultset-ref definition: " + namedSQLQueryDefinition.getResultSetRef());
                }
                spec = new NativeSQLQuerySpecification(namedSQLQueryDefinition.getQueryString(), definition.getQueryReturns(), namedSQLQueryDefinition.getQuerySpaces());
            } else {
                spec = new NativeSQLQuerySpecification(namedSQLQueryDefinition.getQueryString(), namedSQLQueryDefinition.getQueryReturns(), namedSQLQueryDefinition.getQuerySpaces());
            }
            queryPlanCache.getNativeSQLQueryPlan(spec);
        } catch (HibernateException e) {
            errors.put(namedSQLQueryDefinition.getName(), e);
        }
    }
    return errors;
}
Also used : NamedSQLQueryDefinition(org.hibernate.engine.spi.NamedSQLQueryDefinition) HashMap(java.util.HashMap) HibernateException(org.hibernate.HibernateException) NamedQueryDefinition(org.hibernate.engine.spi.NamedQueryDefinition) NativeSQLQuerySpecification(org.hibernate.engine.query.spi.sql.NativeSQLQuerySpecification) ResultSetMappingDefinition(org.hibernate.engine.ResultSetMappingDefinition) MappingException(org.hibernate.MappingException)

Example 68 with HibernateException

use of org.hibernate.HibernateException in project hibernate-orm by hibernate.

the class OrderByFragmentTranslator method translate.

/**
	 * Perform the translation of the user-supplied fragment, returning the translation.
	 * <p/>
	 * The important distinction to this split between (1) translating and (2) resolving aliases is that
	 * both happen at different times
	 *
	 *
	 * @param context Context giving access to delegates needed during translation.
	 * @param fragment The user-supplied order-by fragment
	 *
	 * @return The translation.
	 */
public static OrderByTranslation translate(TranslationContext context, String fragment) {
    GeneratedOrderByLexer lexer = new GeneratedOrderByLexer(new StringReader(fragment));
    // Perform the parsing (and some analysis/resolution).  Another important aspect is the collection
    // of "column references" which are important later to seek out replacement points in the
    // translated fragment.
    OrderByFragmentParser parser = new OrderByFragmentParser(lexer, context);
    try {
        parser.orderByFragment();
    } catch (HibernateException e) {
        throw e;
    } catch (Throwable t) {
        throw new HibernateException("Unable to parse order-by fragment", t);
    }
    if (LOG.isTraceEnabled()) {
        ASTPrinter printer = new ASTPrinter(OrderByTemplateTokenTypes.class);
        LOG.trace(printer.showAsString(parser.getAST(), "--- {order-by fragment} ---"));
    }
    // Render the parsed tree to text.
    OrderByFragmentRenderer renderer = new OrderByFragmentRenderer(context.getSessionFactory());
    try {
        renderer.orderByFragment(parser.getAST());
    } catch (HibernateException e) {
        throw e;
    } catch (Throwable t) {
        throw new HibernateException("Unable to render parsed order-by fragment", t);
    }
    return new StandardOrderByTranslationImpl(renderer.getRenderedFragment(), parser.getColumnReferences());
}
Also used : HibernateException(org.hibernate.HibernateException) ASTPrinter(org.hibernate.hql.internal.ast.util.ASTPrinter) StringReader(java.io.StringReader)

Example 69 with HibernateException

use of org.hibernate.HibernateException in project hibernate-orm by hibernate.

the class JdbcIsolationDelegate method delegateWork.

@Override
public <T> T delegateWork(WorkExecutorVisitable<T> work, boolean transacted) throws HibernateException {
    boolean wasAutoCommit = false;
    try {
        Connection connection = jdbcConnectionAccess().obtainConnection();
        try {
            if (transacted) {
                if (connection.getAutoCommit()) {
                    wasAutoCommit = true;
                    connection.setAutoCommit(false);
                }
            }
            T result = work.accept(new WorkExecutor<T>(), connection);
            if (transacted) {
                connection.commit();
            }
            return result;
        } catch (Exception e) {
            try {
                if (transacted && !connection.isClosed()) {
                    connection.rollback();
                }
            } catch (Exception ignore) {
                LOG.unableToRollbackConnection(ignore);
            }
            if (e instanceof HibernateException) {
                throw (HibernateException) e;
            } else if (e instanceof SQLException) {
                throw sqlExceptionHelper().convert((SQLException) e, "error performing isolated work");
            } else {
                throw new HibernateException("error performing isolated work", e);
            }
        } finally {
            if (transacted && wasAutoCommit) {
                try {
                    connection.setAutoCommit(true);
                } catch (Exception ignore) {
                    LOG.trace("was unable to reset connection back to auto-commit");
                }
            }
            try {
                jdbcConnectionAccess().releaseConnection(connection);
            } catch (Exception ignore) {
                LOG.unableToReleaseIsolatedConnection(ignore);
            }
        }
    } catch (SQLException sqle) {
        throw sqlExceptionHelper().convert(sqle, "unable to obtain isolated JDBC connection");
    }
}
Also used : HibernateException(org.hibernate.HibernateException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) SQLException(java.sql.SQLException) HibernateException(org.hibernate.HibernateException)

Example 70 with HibernateException

use of org.hibernate.HibernateException in project hibernate-orm by hibernate.

the class JtaIsolationDelegate method doInNewTransaction.

private <T> T doInNewTransaction(HibernateCallable<T> callable, TransactionManager transactionManager) {
    try {
        // start the new isolated transaction
        transactionManager.begin();
        try {
            T result = callable.call();
            // if everything went ok, commit the isolated transaction
            transactionManager.commit();
            return result;
        } catch (Exception e) {
            try {
                transactionManager.rollback();
            } catch (Exception ignore) {
                LOG.unableToRollbackIsolatedTransaction(e, ignore);
            }
            throw new HibernateException("Could not apply work", e);
        }
    } catch (SystemException e) {
        throw new HibernateException("Unable to start isolated transaction", e);
    } catch (NotSupportedException e) {
        throw new HibernateException("Unable to start isolated transaction", e);
    }
}
Also used : SystemException(javax.transaction.SystemException) HibernateException(org.hibernate.HibernateException) NotSupportedException(javax.transaction.NotSupportedException) NotSupportedException(javax.transaction.NotSupportedException) SQLException(java.sql.SQLException) SystemException(javax.transaction.SystemException) HibernateException(org.hibernate.HibernateException)

Aggregations

HibernateException (org.hibernate.HibernateException)372 DAOException (org.jbei.ice.storage.DAOException)141 Session (org.hibernate.Session)72 Test (org.junit.Test)41 ArrayList (java.util.ArrayList)30 SQLException (java.sql.SQLException)27 IOException (java.io.IOException)15 TestForIssue (org.hibernate.testing.TestForIssue)15 Transaction (org.hibernate.Transaction)14 Group (org.jbei.ice.storage.model.Group)14 Type (org.hibernate.type.Type)12 PersistenceException (org.mifos.framework.exceptions.PersistenceException)12 Serializable (java.io.Serializable)11 EntityEntry (org.hibernate.engine.spi.EntityEntry)10 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)10 HashMap (java.util.HashMap)9 Method (java.lang.reflect.Method)8 Dialect (org.hibernate.dialect.Dialect)8 CollectionPersister (org.hibernate.persister.collection.CollectionPersister)8 HibernateProxy (org.hibernate.proxy.HibernateProxy)8