Example usage for org.hibernate Session createQuery

List of usage examples for org.hibernate Session createQuery

Introduction

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

Prototype

@Override
    <T> org.hibernate.query.Query<T> createQuery(String queryString, Class<T> resultType);

Source Link

Usage

From source file:be.shad.tsqb.dao.TypeSafeQueryDaoImpl.java

License:Apache License

/**
 * {@inheritDoc}//ww w  .  ja  va 2s  .  c om
 */
@Override
public <T> QueryResult<T> doQuery(TypeSafeRootQuery tsqbQuery, HibernateQueryConfigurer configurer) {
    HqlQuery hqlQuery = tsqbQuery.toHqlQuery();

    Session currentSession = sessionFactory.getCurrentSession();
    Query<Object[]> query = currentSession.createQuery(hqlQuery.getHql(), Object[].class);
    int position = 0;
    CollectionNamedParameter chunkedParam = null;
    for (Object param : hqlQuery.getParams()) {
        if (param instanceof NamedParameter) {
            NamedParameter named = (NamedParameter) param;
            if (isChunkedParam(named)) {
                if (chunkedParam != null) {
                    throw new IllegalStateException(
                            String.format("More than one batched param [%s, %s] was used in query [%s].",
                                    chunkedParam.getName(), named.getName(), query.getQueryString()));
                }
                // remember batched param to bind iterate and bind chunks later:
                chunkedParam = (CollectionNamedParameter) named;
            } else if (named.getValue() instanceof Collection) {
                query.setParameterList(named.getName(), (Collection<?>) named.getValue());
            } else {
                query.setParameter(named.getName(), named.getValue());
            }
        } else {
            query.setParameter(position++, param);
        }
    }
    if (tsqbQuery.getFirstResult() >= 0) {
        query.setFirstResult(tsqbQuery.getFirstResult());
    }
    if (tsqbQuery.getMaxResults() > 0) {
        query.setMaxResults(tsqbQuery.getMaxResults());
    }

    List<T> results = null;
    if (configurer != null) {
        configurer.beforeQuery(currentSession);
        configurer.configureQuery(query);
        try {
            results = listAll(query, hqlQuery, chunkedParam);
        } finally {
            configurer.afterQuery(currentSession);
        }
    } else {
        results = listAll(query, hqlQuery, chunkedParam);
    }
    return new QueryResult<>(results);
}