Example usage for org.hibernate QueryException QueryException

List of usage examples for org.hibernate QueryException QueryException

Introduction

In this page you can find the example usage for org.hibernate QueryException QueryException.

Prototype

public QueryException(Exception cause) 

Source Link

Document

Constructs a QueryException using the specified cause.

Usage

From source file:com.mothsoft.alexis.dao.DocumentDaoImpl.java

License:Apache License

private FullTextQuery buildFullTextQuery(final String queryString, final Long userId, final Date startDate,
        final Date endDate, final boolean requireTopicsForUser, final DocumentState state,
        final String... projectionConstants) {
    final String[] fields = new String[] { "title", "description", CONTENT_TEXT_FIELD_NAME, "author" };
    final MultiFieldQueryParser parser = new MultiFieldQueryParser(Version.LUCENE_35, fields,
            new StandardAnalyzer(Version.LUCENE_35));

    org.apache.lucene.search.BooleanQuery compositeQuery = new org.apache.lucene.search.BooleanQuery();

    if (queryString != null) {
        org.apache.lucene.search.Query luceneTextQuery;
        try {/*w w  w.j a  va  2s.c o m*/
            luceneTextQuery = parser.parse(queryString);
            compositeQuery.add(luceneTextQuery, Occur.MUST);
        } catch (ParseException e) {
            throw new QueryException(e);
        }
    }

    org.apache.lucene.search.Query luceneSecurityQuery = NumericRangeQuery.newLongRange("user", userId, userId,
            true, true);
    compositeQuery.add(luceneSecurityQuery, Occur.MUST);

    if (startDate != null || endDate != null) {
        final Long startMillis = startDate == null ? 0 : startDate.getTime();
        final Long endMillis = endDate == null ? Long.MAX_VALUE : endDate.getTime();
        org.apache.lucene.search.Query dateRangeQuery = NumericRangeQuery.newLongRange("creationDate",
                startMillis, endMillis, true, true);
        compositeQuery.add(dateRangeQuery, Occur.MUST);
    }

    if (requireTopicsForUser) {
        org.apache.lucene.search.Query topicUserQuery = NumericRangeQuery.newLongRange("topicUser", userId,
                userId, true, true);
        compositeQuery.add(topicUserQuery, Occur.MUST);
    }

    if (state != null) {
        final int stateInt = state.getValue();
        org.apache.lucene.search.Query stateQuery = NumericRangeQuery.newIntRange("state", stateInt, stateInt,
                true, true);
        compositeQuery.add(stateQuery, Occur.MUST);
    }

    final Session session = (Session) this.em.getDelegate();
    final FullTextSession fullTextSession = Search.getFullTextSession(session);
    final FullTextQuery fullTextQuery = fullTextSession.createFullTextQuery(compositeQuery)
            .setProjection(projectionConstants);
    return fullTextQuery;
}

From source file:org.babyfish.hibernate.dialect.OracleDistinctLimits.java

License:Open Source License

public static void install(SessionFactoryImplementor sfi) {
    if (!SettingsFactory.isDistinctRankCreateable(sfi.getProperties())) {
        return;/* w  w  w  . j a va  2 s .  com*/
    }
    LOGGER.info(LOGGER_RESOURCE.tryToCreateAnalyticFunction(SettingsFactory.CREATE_ORACLE_DISTINCT_RANK, "true",
            DISTINCT_RANK));
    StatelessSession sls = sfi.openStatelessSession();
    try {
        Connection con = ((SessionImplementor) sls).connection();
        installPLSQLWrapper(con);
    } catch (SQLException ex) {
        throw new QueryException(ex);
    } catch (IOException ex) {
        throw new HibernateException("Can not install the installable dialect", ex);
    } finally {
        sls.close();
    }
}

From source file:org.babyfish.hibernate.hql.XQueryPlan.java

License:Open Source License

public <T> List<T> performList(SessionImplementor session, QueryParameters queryParameters,
        QueryType queryMode) {// w  ww .j  a  v  a 2 s  .c o m
    if (log.isTraceEnabled()) {
        log.trace("find: " + getSourceQuery());
        queryParameters.traceParameters(session.getFactory());
    }
    QueryTranslator[] translators = this.getTranslators();
    boolean hasLimit = queryParameters.getRowSelection() != null
            && queryParameters.getRowSelection().definesLimits();
    boolean needsMemoryLimit = hasLimit && translators.length > 1;
    QueryParameters queryParametersToUse;
    if (needsMemoryLimit) {
        if (!SettingsFactory.isLimitInMemoryEnabled(session.getFactory().getProperties())) {
            throw new QueryException(LAZY_RESOURCE.get().hibernateLimitInMemoryForPolymorphicQueryIsNotEnabled(
                    SettingsFactory.ENABLE_LIMIT_IN_MEMORY));
        }
        log.warn("firstResult/maxResults specified on polymorphic query; applying in memory!");
        RowSelection selection = new RowSelection();
        selection.setFetchSize(queryParameters.getRowSelection().getFetchSize());
        selection.setTimeout(queryParameters.getRowSelection().getTimeout());
        queryParametersToUse = queryParameters.createCopyUsing(selection);
    } else {
        queryParametersToUse = queryParameters;
    }

    List<T> combinedResults = new ArrayList<T>();
    Set<T> distinction = new LinkedHashSet<T>(ReferenceEqualityComparator.getInstance());
    int includedCount = -1;
    translator_loop: for (int i = 0; i < translators.length; i++) {
        List<T> tmp = ((XQueryTranslator) translators[i]).list(session, queryParametersToUse, queryMode);
        if (needsMemoryLimit) {
            // NOTE : firstRow is zero-based
            int first = queryParameters.getRowSelection().getFirstRow() == null ? 0
                    : queryParameters.getRowSelection().getFirstRow().intValue();
            int max = queryParameters.getRowSelection().getMaxRows() == null ? -1
                    : queryParameters.getRowSelection().getMaxRows().intValue();
            final int size = tmp.size();
            for (int x = 0; x < size; x++) {
                final T result = tmp.get(x);
                if (!distinction.add(result)) {
                    continue;
                }
                includedCount++;
                if (includedCount < first) {
                    continue;
                }
                combinedResults.add(result);
                if (max >= 0 && includedCount > max) {
                    break translator_loop; // break the outer loop !!!
                }
            }
        } else {
            if (translators.length == 1) {
                return tmp;
            } else {
                combinedResults.addAll(tmp);
            }
        }
    }
    return combinedResults;
}

From source file:org.babyfish.hibernate.hql.XQueryTranslatorImpl.java

License:Open Source License

@Override
public long unlimitedCount(SessionImplementor session, QueryParameters queryParameters, QueryType queryType) {
    if (this.unlimitedCountExceptionCreator != null) {
        throw this.unlimitedCountExceptionCreator.create();
    }//from   w w w. j  a  va2 s. co  m
    UnlimitedCountLoader loader;
    if (queryType == QueryType.DISTINCT && this.distinctCountLoader != null) {
        loader = this.distinctCountLoader;
    } else {
        loader = this.countLoader;
    }
    if (loader == null) {
        throw new QueryException(LAZY_RESOURCE.get().operationRequiresQuery("unlimitedCount"));
    }
    List<?> list = loader.list(session, queryParameters);
    Object o = list.iterator().next();
    if (o.getClass().isArray()) {
        o = ((Object[]) o)[0];
    }
    if (o instanceof Long) {
        return (Long) o;
    }
    if (o instanceof Integer) {
        return (Integer) o;
    }
    return Long.parseLong(o.toString());
}

From source file:org.babyfish.hibernate.hql.XQueryTranslatorImpl.java

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override/*from   w w  w. j a  va  2  s.  c o m*/
public <T> List<T> list(SessionImplementor session, QueryParameters queryParameters, QueryType queryType) {
    if (queryType == QueryType.DISTINCT) {
        List<T> tmp;
        if (this.distinctLimitQueryLoader != null) {
            tmp = (List) this.distinctLimitQueryLoader.list(session, queryParameters);
        } else {
            boolean hasLimit = queryParameters.getRowSelection() != null
                    && queryParameters.getRowSelection().definesLimits();
            if (hasLimit && this.containsCollectionFetches()) {
                if (!SettingsFactory.isLimitInMemoryEnabled(session.getFactory().getProperties())) {
                    throw new QueryException(LAZY_RESOURCE.get()
                            .hibernateLimitInMemoryForCollectionFetchIsNotEnabled(DistinctLimitDialect.class,
                                    Oracle10gDialect.class, SettingsFactory.ENABLE_LIMIT_IN_MEMORY));
                }
            }
            tmp = this.list(session, queryParameters);
        }
        Set<T> distinction = new LinkedHashSet<T>(ReferenceEqualityComparator.getInstance());
        distinction.addAll(tmp);
        List<T> results = new ArrayList<T>(distinction.size());
        results.addAll(distinction);
        this.applyScalarEagerness(results, session);
        return results;
    } else {
        return this.queryLoader.list(session, queryParameters);
    }
}

From source file:org.babyfish.hibernate.hql.XQueryTranslatorImpl.java

License:Open Source License

private void initialize(AST ast) {
    if (this.pathPlan == null) {
        if (ast.getType() != HqlTokenTypes.QUERY) {
            if (this.pathPlanKey != null) {
                throw new QueryException(LAZY_RESOURCE.get().queryPathsCanNotBeApplyToNonQuery(this.hql));
            }//w ww. j  a va  2  s .  c o m
        } else {
            this.pathPlan = new PathPlanFactoryImpl(this.factory, ast).create(this.pathPlanKey);
            if (HqlASTHelper.findFirstChildInToppestQuery(ast, HqlTokenTypes.SELECT) == null
                    && this.pathPlan.containsNoFetchJoins()) {
                throw new QueryException(LAZY_RESOURCE.get()
                        .hqlMustContainsSelectCaluseWhenThereIsNoFetchJoinInQueryPaths(this.hql));
            }
            this.startFromElementASTMap = this.createStartFromElementASTMap(ast);
        }
    }
}

From source file:org.babyfish.hibernate.hql.XQueryTranslatorImpl.java

License:Open Source License

private ExceptionCreator getUnlimitedCountExceptionCreator(AST ast) {
    final String hql = this.hql;
    AST groupAst = HqlASTHelper.findFirstChildInToppestQuery(ast, HqlTokenTypes.GROUP);
    if (groupAst != null) {
        return new ExceptionCreator() {
            @Override// w  w  w  . ja va 2 s  .c  om
            public RuntimeException create() {
                return new QueryException(LAZY_RESOURCE.get().unlimitedCountIsUnsupportedBecauseOfGroupBy(hql));
            }
        };
    }
    AST selectFromAst = HqlASTHelper.findFirstChildInToppestQuery(ast, HqlTokenTypes.SELECT_FROM);
    AST selectAst = HqlASTHelper.findFirstChildInToppestQuery(selectFromAst, HqlTokenTypes.SELECT);
    if (selectAst != null) {
        AST selectionAst = selectAst.getFirstChild();
        if (selectionAst.getNextSibling() != null) {
            return new ExceptionCreator() {
                @Override
                public RuntimeException create() {
                    return new QueryException(
                            LAZY_RESOURCE.get().unlimitedCountIsUnsupportedBecauseOfTooManySelections(hql));
                }
            };
        }
        boolean selectRootEntity = false;
        if (selectionAst.getType() == HqlTokenTypes.IDENT) {
            AST firstRangeAst = HqlASTHelper.findFirstChildInToppestQuery(selectFromAst, HqlTokenTypes.RANGE);
            String alias = HqlASTHelper.getAlias(firstRangeAst);
            selectRootEntity = selectionAst.getText().equals(alias);
        }
        if (!selectRootEntity) {
            return new ExceptionCreator() {
                @Override
                public RuntimeException create() {
                    return new QueryException(LAZY_RESOURCE.get()
                            .unlimitedCountIsUnsupportedBecauseSelectionIsNotRootEntity(hql));
                }
            };
        }
    } else {
        boolean metRange = false;
        AST fromAst = HqlASTHelper.findFirstChildInToppestQuery(selectFromAst, HqlTokenTypes.FROM);
        for (AST fromElementAst = fromAst
                .getFirstChild(); fromElementAst != null; fromElementAst = fromElementAst.getNextSibling()) {
            if (fromElementAst.getType() == HqlTokenTypes.RANGE) {
                if (metRange) {
                    return new ExceptionCreator() {
                        @Override
                        public RuntimeException create() {
                            return new QueryException(LAZY_RESOURCE.get()
                                    .unlimitedCountIsUnsupportedBecauseOfTooManyRangeAndNoSelection(hql));
                        }
                    };
                }
                metRange = true;
            } else {
                AST fetchAst = HqlASTHelper.findFirstChildInToppestQuery(fromElementAst, HqlTokenTypes.FETCH);
                if (fetchAst == null) {
                    return new ExceptionCreator() {
                        @Override
                        public RuntimeException create() {
                            return new QueryException(LAZY_RESOURCE.get()
                                    .unlimitedCountIsUnsupportedBecauseOfNonFetchJoinsAndNoSelection(hql));
                        }
                    };
                }
            }
        }
    }
    return null;
}

From source file:org.openxma.dsl.platform.hibernate.NamedQueryFilter.java

License:Open Source License

private String rewriteHqlQuery(QueryObject queryObject) {
    NamedQueryDefinition namedQueryDefinition = sessionFactoryImplementor
            .getNamedQuery(queryObject.getQueryName());
    if (namedQueryDefinition == null) {
        throw new QueryException("NameQuery '" + queryObject.getQueryName() + "' not found");
    }//  ww  w .ja v  a2s. c  om
    String hqlQueryString = namedQueryDefinition.getQueryString();
    rewritingHqlParser = RewritingHqlParser.getInstance(hqlQueryString, sessionFactoryImplementor);
    rewritingHqlParser.setRewritingStrategy(this);
    try {
        rewritingHqlParser.statement();
    } catch (ANTLRException e) {
        throw new QueryException(e.getMessage(), hqlQueryString);
    }
    return rewritingHqlParser.rewriteHqlQuery();
}

From source file:org.springframework.orm.hibernate3.HibernateTemplateTests.java

License:Apache License

@Test
public void testExceptions() throws HibernateException {
    SQLException sqlEx = new SQLException("argh", "27");

    final JDBCConnectionException jcex = new JDBCConnectionException("mymsg", sqlEx);
    try {/*from   ww  w . ja  va  2  s .c om*/
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw jcex;
            }
        });
        fail("Should have thrown DataAccessResourceFailureException");
    } catch (DataAccessResourceFailureException ex) {
        // expected
        assertEquals(jcex, ex.getCause());
        assertTrue(ex.getMessage().indexOf("mymsg") != -1);
    }

    final SQLGrammarException sgex = new SQLGrammarException("mymsg", sqlEx);
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw sgex;
            }
        });
        fail("Should have thrown InvalidDataAccessResourceUsageException");
    } catch (InvalidDataAccessResourceUsageException ex) {
        // expected
        assertEquals(sgex, ex.getCause());
        assertTrue(ex.getMessage().indexOf("mymsg") != -1);
    }

    final LockAcquisitionException laex = new LockAcquisitionException("mymsg", sqlEx);
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw laex;
            }
        });
        fail("Should have thrown CannotAcquireLockException");
    } catch (CannotAcquireLockException ex) {
        // expected
        assertEquals(laex, ex.getCause());
        assertTrue(ex.getMessage().indexOf("mymsg") != -1);
    }

    final ConstraintViolationException cvex = new ConstraintViolationException("mymsg", sqlEx, "myconstraint");
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw cvex;
            }
        });
        fail("Should have thrown DataIntegrityViolationException");
    } catch (DataIntegrityViolationException ex) {
        // expected
        assertEquals(cvex, ex.getCause());
        assertTrue(ex.getMessage().indexOf("mymsg") != -1);
    }

    final DataException dex = new DataException("mymsg", sqlEx);
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw dex;
            }
        });
        fail("Should have thrown DataIntegrityViolationException");
    } catch (DataIntegrityViolationException ex) {
        // expected
        assertEquals(dex, ex.getCause());
        assertTrue(ex.getMessage().indexOf("mymsg") != -1);
    }

    final JDBCException jdex = new JDBCException("mymsg", sqlEx);
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw jdex;
            }
        });
        fail("Should have thrown HibernateJdbcException");
    } catch (HibernateJdbcException ex) {
        // expected
        assertEquals(jdex, ex.getCause());
        assertTrue(ex.getMessage().indexOf("mymsg") != -1);
    }

    final PropertyValueException pvex = new PropertyValueException("mymsg", "myentity", "myproperty");
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw pvex;
            }
        });
        fail("Should have thrown DataIntegrityViolationException");
    } catch (DataIntegrityViolationException ex) {
        // expected
        assertEquals(pvex, ex.getCause());
        assertTrue(ex.getMessage().indexOf("mymsg") != -1);
    }

    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw new PersistentObjectException("");
            }
        });
        fail("Should have thrown InvalidDataAccessApiUsageException");
    } catch (InvalidDataAccessApiUsageException ex) {
        // expected
    }

    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw new TransientObjectException("");
            }
        });
        fail("Should have thrown InvalidDataAccessApiUsageException");
    } catch (InvalidDataAccessApiUsageException ex) {
        // expected
    }

    final ObjectDeletedException odex = new ObjectDeletedException("msg", "id", TestBean.class.getName());
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw odex;
            }
        });
        fail("Should have thrown InvalidDataAccessApiUsageException");
    } catch (InvalidDataAccessApiUsageException ex) {
        // expected
        assertEquals(odex, ex.getCause());
    }

    final QueryException qex = new QueryException("msg");
    qex.setQueryString("query");
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw qex;
            }
        });
        fail("Should have thrown InvalidDataAccessResourceUsageException");
    } catch (HibernateQueryException ex) {
        // expected
        assertEquals(qex, ex.getCause());
        assertEquals("query", ex.getQueryString());
    }

    final UnresolvableObjectException uoex = new UnresolvableObjectException("id", TestBean.class.getName());
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw uoex;
            }
        });
        fail("Should have thrown HibernateObjectRetrievalFailureException");
    } catch (HibernateObjectRetrievalFailureException ex) {
        // expected
        assertEquals(TestBean.class.getName(), ex.getPersistentClassName());
        assertEquals("id", ex.getIdentifier());
        assertEquals(uoex, ex.getCause());
    }

    final ObjectNotFoundException onfe = new ObjectNotFoundException("id", TestBean.class.getName());
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw onfe;
            }
        });
        fail("Should have thrown HibernateObjectRetrievalFailureException");
    } catch (HibernateObjectRetrievalFailureException ex) {
        // expected
        assertEquals(TestBean.class.getName(), ex.getPersistentClassName());
        assertEquals("id", ex.getIdentifier());
        assertEquals(onfe, ex.getCause());
    }

    final WrongClassException wcex = new WrongClassException("msg", "id", TestBean.class.getName());
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw wcex;
            }
        });
        fail("Should have thrown HibernateObjectRetrievalFailureException");
    } catch (HibernateObjectRetrievalFailureException ex) {
        // expected
        assertEquals(TestBean.class.getName(), ex.getPersistentClassName());
        assertEquals("id", ex.getIdentifier());
        assertEquals(wcex, ex.getCause());
    }

    final NonUniqueResultException nuex = new NonUniqueResultException(2);
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw nuex;
            }
        });
        fail("Should have thrown IncorrectResultSizeDataAccessException");
    } catch (IncorrectResultSizeDataAccessException ex) {
        // expected
        assertEquals(1, ex.getExpectedSize());
        assertEquals(-1, ex.getActualSize());
    }

    final StaleObjectStateException sosex = new StaleObjectStateException(TestBean.class.getName(), "id");
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw sosex;
            }
        });
        fail("Should have thrown HibernateOptimisticLockingFailureException");
    } catch (HibernateOptimisticLockingFailureException ex) {
        // expected
        assertEquals(TestBean.class.getName(), ex.getPersistentClassName());
        assertEquals("id", ex.getIdentifier());
        assertEquals(sosex, ex.getCause());
    }

    final StaleStateException ssex = new StaleStateException("msg");
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw ssex;
            }
        });
        fail("Should have thrown HibernateOptimisticLockingFailureException");
    } catch (HibernateOptimisticLockingFailureException ex) {
        // expected
        assertNull(ex.getPersistentClassName());
        assertNull(ex.getIdentifier());
        assertEquals(ssex, ex.getCause());
    }

    final HibernateException hex = new HibernateException("msg");
    try {
        hibernateTemplate.execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(org.hibernate.Session session) throws HibernateException {
                throw hex;
            }
        });
        fail("Should have thrown HibernateSystemException");
    } catch (HibernateSystemException ex) {
        // expected
        assertEquals(hex, ex.getCause());
    }
}

From source file:solidstack.query.hibernate.HibernateSupport.java

License:Apache License

/**
 * Creates a Hibernate query./*from ww w .  j  a va  2  s.co m*/
 *
 * @param query The query.
 * @param session A Hibernate session.
 * @param args The arguments to the query. When a map, then the contents of the map. When an Object, then the JavaBean properties.
 * @return The Hibernate query.
 */
static public org.hibernate.Query createQuery(Query query, Session session, Object args) {
    PreparedSQL preparedSql = query.getPreparedSQL(args);

    org.hibernate.Query result;
    if (query.getLanguage() == Language.SQL)
        result = session.createSQLQuery(preparedSql.getSQL());
    else if (query.getLanguage() == Language.HQL)
        result = session.createQuery(preparedSql.getSQL());
    else
        throw new QueryException("Query type '" + query.getLanguage() + "' not recognized");

    List<Object> pars = preparedSql.getParameters();
    int i = 0;
    for (Object par : pars) {
        if (par != null) {
            Assert.isFalse(par instanceof Collection);
            Assert.isFalse(par.getClass().isArray());
        }
        result.setParameter(i++, par);
    }
    return result;
}