Example usage for javax.persistence Query setHint

List of usage examples for javax.persistence Query setHint

Introduction

In this page you can find the example usage for javax.persistence Query setHint.

Prototype

Query setHint(String hintName, Object value);

Source Link

Document

Set a query property or hint.

Usage

From source file:com.webbfontaine.valuewebb.action.rimm.RefSelect.java

public List selectRefData(String refName, boolean retrieveDsc, String sortColumn, boolean isCacheEnabled) {
    String sql = "select ref.cod " + (retrieveDsc ? ", ref.dsc, ref.dscFr " : "") + " from " + refName
            + " ref ";
    if (sortColumn != null) {
        sql += " order by ref." + sortColumn;
    }/*from   w ww .  j a v a2 s.  c o m*/

    Query query = Utils.getEntityManager().createQuery(sql);
    if (isCacheEnabled) {
        query.setHint("org.hibernate.cacheable", true);
    }
    return query.getResultList();
}

From source file:com.webbfontaine.valuewebb.action.rimm.RefSelect.java

/**
 * Retrieves Rate object for requested currency and date
 *
 * @param forDate  null means today. Every value is truncated - seconds, minutes, hours are removed.
 * @param currency requested currency//w w  w.  ja  v a 2 s .  com
 * @return {@link com.webbfontaine.valuewebb.model.rimm.Rate#EMPTY_INSTANCE} object if rate does not exist for currency
 */
public Rate getRate(Date forDate, String currency) {
    if (Utils.getNationalCurrencyName().equals(currency)) {
        return getNationalCurrencyRate();
    }

    if (forDate == null || currency == null) {
        return Rate.EMPTY_INSTANCE;
    }

    Query query = Utils.getEntityManager().createNamedQuery("rateByCurrencyAndDate");
    query.setHint("org.hibernate.cacheable", false);
    query.setParameter("cod", currency);
    query.setParameter("date", DateUtils.truncate(forDate, Calendar.DAY_OF_MONTH));

    try {
        return (Rate) query.getSingleResult();
    } catch (Exception e) {
        LOGGER.warn("Rate for currency [{0}] couldn't be obtained", currency);
    }
    return Rate.EMPTY_INSTANCE;
}

From source file:de.micromata.genome.jpa.Emgr.java

@Override
public void setQueryTimeout(Query query, int timeOutInMs) {
    // "javax.persistence.query.timeout"
    // javax.persistence.lock.timeout

    query.setHint(HINT_QUERY_TIMEOUT, timeOutInMs);
}

From source file:net.nan21.dnet.core.presenter.action.query.QueryBuilderWithJpql.java

protected void addFetchGroup(Query q) {
    // see the reason of forExport flag
    boolean disableFecthGroups = this.getSettings().getAsBoolean(Constants.PROP_DISABLE_FETCH_GROUPS);
    if (this.forExport || disableFecthGroups)
        return;//  w ww .j av a  2  s .c  om
    logger.debug("Adding fetchGroup...");
    FetchGroup fg = new FetchGroup("default");
    fg.setShouldLoad(true);

    if (this.getDescriptor().getRefPaths() != null) {
        Map<String, String> refPaths = this.getDescriptor().getRefPaths();
        Iterator<String> it = refPaths.keySet().iterator();
        while (it.hasNext()) {
            String p = it.next();
            fg.addAttribute(refPaths.get(p));
        }
        q.setHint(QueryHints.FETCH_GROUP, fg);
    }
}

From source file:org.mingle.pear.persistence.dao.impl.GenericDaoImpl.java

/**
 * ??//from   w  w w  . j a  v  a  2s .c o  m
 *
 * @param qt
 * @param clazz
 * @return
 */
protected <R> Query createQuery(QueryTemplate qt, Class<R> clazz) {
    Query query = null;
    if (qt instanceof JqlQueryTemplate) {
        if (clazz == null) {
            query = entityManager().createQuery(qt.getQuery());
        } else {
            query = entityManager().createQuery(qt.getQuery(), clazz);
        }
    }
    if (qt instanceof NamedQueryTemplate) {
        if (clazz == null) {
            query = entityManager().createNamedQuery(qt.getQuery());
        } else {
            query = entityManager().createNamedQuery(qt.getQuery(), clazz);
        }
    }
    if (qt instanceof SqlQueryTemplate) {
        query = entityManager().createNativeQuery(qt.getQuery());
    }
    if (qt instanceof SqlResultSetMappingQueryTemplate) {
        SqlResultSetMappingQueryTemplate sqt = (SqlResultSetMappingQueryTemplate) qt;
        query = entityManager().createNativeQuery(qt.getQuery(), sqt.getSqlResultMapping());
    }
    // ?
    if (qt.getParameters() != null) {
        for (Entry<String, ?> paramEntry : qt.getParameters().entrySet()) {
            query.setParameter(paramEntry.getKey(), paramEntry.getValue());
        }
    }
    // 
    if (qt.isCachable()) {
        query.setHint("org.hibernate.cacheable", true);
        if (StringUtils.isNotBlank(qt.getCacheRegion())) {
            query.setHint("org.hibernate.cacheRegion", qt.getCacheRegion());
        } else {
            query.setHint("org.hibernate.cacheRegion", clazz.getName());
        }
    }
    // 
    query.setFirstResult(qt.getFirstResult());
    query.setMaxResults(qt.getMaxResults());
    return query;
}

From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java

private void setQueryTimeout(Query q) {
    q.setHint("org.hibernate.timeout", new Integer(60));
}

From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java

public List<INakedObject> fillResultList(String className, EntityManager em, Set<PropertyDescriptor> ids,
        List<String> idFieldNames, Query q, boolean hasOrder)
        throws ClassNotFoundException, InstantiationException, IllegalAccessException {
    q.setHint("org.hibernate.readOnly", Boolean.TRUE);
    List<Object[]> ll = q.getResultList();
    if (ll != null && !ll.isEmpty()) {
        boolean single = ids.size() == 1;
        Object pk = null;/* ww w.  j  ava2s . com*/
        Class<?> c = Class.forName(className);
        Class clazz = null;
        if (!single) {
            IdClass idClass = c.getAnnotation(IdClass.class);
            clazz = idClass.value();
            pk = clazz.newInstance();
        }
        List<INakedObject> list = new ArrayList<>(ll.size());
        for (Object o : ll) {
            if (single) {
                list.add((INakedObject) em.find(c, hasOrder ? ((Object[]) o)[0] : o));
            } else {
                for (Field f : clazz.getDeclaredFields()) {
                    int idx = idFieldNames.indexOf(f.getName());
                    if (idx >= 0) {
                        boolean b = false;
                        if (!f.isAccessible()) {
                            f.setAccessible(true);
                            b = true;
                        }
                        f.set(pk, ((Object[]) o)[idx]);
                        if (b)
                            f.setAccessible(false);
                    }
                }
                list.add((INakedObject) em.find(c, pk));
            }
        }
        return list;
    }
    return null;
}

From source file:org.ejbca.core.model.era.RaMasterApiSessionBean.java

@SuppressWarnings("unchecked")
@Override//from   ww  w  .  j a v a 2s.c om
public RaEndEntitySearchResponse searchForEndEntities(AuthenticationToken authenticationToken,
        RaEndEntitySearchRequest request) {
    final RaEndEntitySearchResponse response = new RaEndEntitySearchResponse();
    final List<Integer> authorizedLocalCaIds = new ArrayList<>(
            caSession.getAuthorizedCaIds(authenticationToken));
    // Only search a subset of the requested CAs if requested
    if (!request.getCaIds().isEmpty()) {
        authorizedLocalCaIds.retainAll(request.getCaIds());
    }
    if (authorizedLocalCaIds.isEmpty()) {
        // Empty response since there were no authorized CAs
        if (log.isDebugEnabled()) {
            log.debug("Client '" + authenticationToken
                    + "' was not authorized to any of the requested CAs and the search request will be dropped.");
        }
        return response;
    }
    // Check Certificate Profile authorization
    final List<Integer> authorizedCpIds = new ArrayList<>(
            certificateProfileSession.getAuthorizedCertificateProfileIds(authenticationToken, 0));
    final boolean accessAnyCpAvailable = authorizedCpIds
            .containsAll(certificateProfileSession.getCertificateProfileIdToNameMap().keySet());
    if (!request.getCpIds().isEmpty()) {
        authorizedCpIds.retainAll(request.getCpIds());
    }
    if (authorizedCpIds.isEmpty()) {
        // Empty response since there were no authorized Certificate Profiles
        if (log.isDebugEnabled()) {
            log.debug("Client '" + authenticationToken
                    + "' was not authorized to any of the requested CPs and the search request will be dropped.");
        }
        return response;
    }
    // Check End Entity Profile authorization
    final Collection<Integer> authorizedEepIds = new ArrayList<>(endEntityProfileSession
            .getAuthorizedEndEntityProfileIds(authenticationToken, AccessRulesConstants.VIEW_END_ENTITY));
    final boolean accessAnyEepAvailable = authorizedEepIds
            .containsAll(endEntityProfileSession.getEndEntityProfileIdToNameMap().keySet());
    if (!request.getEepIds().isEmpty()) {
        authorizedEepIds.retainAll(request.getEepIds());
    }
    if (authorizedEepIds.isEmpty()) {
        // Empty response since there were no authorized End Entity Profiles
        if (log.isDebugEnabled()) {
            log.debug("Client '" + authenticationToken
                    + "' was not authorized to any of the requested EEPs and the search request will be dropped.");
        }
        return response;
    }
    final String subjectDnSearchString = request.getSubjectDnSearchString();
    final String subjectAnSearchString = request.getSubjectAnSearchString();
    final String usernameSearchString = request.getUsernameSearchString();
    final StringBuilder sb = new StringBuilder("SELECT a.username FROM UserData a WHERE (a.caId IN (:caId))");
    if (!subjectDnSearchString.isEmpty() || !subjectAnSearchString.isEmpty()
            || !usernameSearchString.isEmpty()) {
        sb.append(" AND (");
        boolean firstAppended = false;
        if (!subjectDnSearchString.isEmpty()) {
            sb.append("a.subjectDN LIKE :subjectDN");
            firstAppended = true;
        }
        if (!subjectAnSearchString.isEmpty()) {
            if (firstAppended) {
                sb.append(" OR ");
            } else {
                firstAppended = true;
            }
            sb.append("a.subjectAltName LIKE :subjectAltName");
        }
        if (!usernameSearchString.isEmpty()) {
            if (firstAppended) {
                sb.append(" OR ");
            } else {
                firstAppended = true;
            }
            sb.append("a.username LIKE :username");
        }
        sb.append(")");
    }

    if (request.isModifiedAfterUsed()) {
        sb.append(" AND (a.timeModified > :modifiedAfter)");
    }
    if (request.isModifiedBeforeUsed()) {
        sb.append(" AND (a.timeModified < :modifiedBefore)");
    }
    if (!request.getStatuses().isEmpty()) {
        sb.append(" AND (a.status IN (:status))");
    }
    // Don't constrain results to certain end entity profiles if root access is available and "any" CP is requested
    if (!accessAnyCpAvailable || !request.getCpIds().isEmpty()) {
        sb.append(" AND (a.certificateProfileId IN (:certificateProfileId))");
    }
    // Don't constrain results to certain end entity profiles if root access is available and "any" EEP is requested
    if (!accessAnyEepAvailable || !request.getEepIds().isEmpty()) {
        sb.append(" AND (a.endEntityProfileId IN (:endEntityProfileId))");
    }
    final Query query = entityManager.createQuery(sb.toString());
    query.setParameter("caId", authorizedLocalCaIds);
    if (!accessAnyCpAvailable || !request.getCpIds().isEmpty()) {
        query.setParameter("certificateProfileId", authorizedCpIds);
    }
    if (!accessAnyEepAvailable || !request.getEepIds().isEmpty()) {
        query.setParameter("endEntityProfileId", authorizedEepIds);
    }
    if (log.isDebugEnabled()) {
        log.debug(" CA IDs: " + Arrays.toString(authorizedLocalCaIds.toArray()));
        if (!accessAnyCpAvailable || !request.getCpIds().isEmpty()) {
            log.debug(" certificateProfileId: " + Arrays.toString(authorizedCpIds.toArray()));
        } else {
            log.debug(" certificateProfileId: Any (even deleted) profile(s) due to root access.");
        }
        if (!accessAnyEepAvailable || !request.getEepIds().isEmpty()) {
            log.debug(" endEntityProfileId: " + Arrays.toString(authorizedEepIds.toArray()));
        } else {
            log.debug(" endEntityProfileId: Any (even deleted) profile(s) due to root access.");
        }
    }
    if (!subjectDnSearchString.isEmpty()) {
        if (request.isSubjectDnSearchExact()) {
            query.setParameter("subjectDN", subjectDnSearchString);
        } else {
            query.setParameter("subjectDN", "%" + subjectDnSearchString + "%");
        }
    }
    if (!subjectAnSearchString.isEmpty()) {
        if (request.isSubjectAnSearchExact()) {
            query.setParameter("subjectAltName", subjectAnSearchString);
        } else {
            query.setParameter("subjectAltName", "%" + subjectAnSearchString + "%");
        }
    }
    if (!usernameSearchString.isEmpty()) {
        if (request.isUsernameSearchExact()) {
            query.setParameter("username", usernameSearchString);
        } else {
            query.setParameter("username", "%" + usernameSearchString + "%");
        }
    }
    if (request.isModifiedAfterUsed()) {
        query.setParameter("modifiedAfter", request.getModifiedAfter());
    }
    if (request.isModifiedBeforeUsed()) {
        query.setParameter("modifiedBefore", request.getModifiedBefore());
    }
    if (!request.getStatuses().isEmpty()) {
        query.setParameter("status", request.getStatuses());
    }
    final int maxResults = Math.min(getGlobalCesecoreConfiguration().getMaximumQueryCount(),
            request.getMaxResults());
    query.setMaxResults(maxResults);
    /* Try to use the non-portable hint (depends on DB and JDBC driver) to specify how long in milliseconds the query may run. Possible behaviors:
     * - The hint is ignored
     * - A QueryTimeoutException is thrown
     * - A PersistenceException is thrown (and the transaction which don't have here is marked for roll-back)
     */
    final long queryTimeout = getGlobalCesecoreConfiguration().getMaximumQueryTimeout();
    if (queryTimeout > 0L) {
        query.setHint("javax.persistence.query.timeout", String.valueOf(queryTimeout));
    }
    final List<String> usernames;
    try {
        usernames = query.getResultList();
        for (final String username : usernames) {
            response.getEndEntities().add(endEntityAccessSession.findUser(username));
        }
        response.setMightHaveMoreResults(usernames.size() == maxResults);
        if (log.isDebugEnabled()) {
            log.debug("Certificate search query: " + sb.toString() + " LIMIT " + maxResults + " \u2192 "
                    + usernames.size() + " results. queryTimeout=" + queryTimeout + "ms");
        }
    } catch (QueryTimeoutException e) {
        log.info("Requested search query by " + authenticationToken + " took too long. Query was "
                + e.getQuery().toString() + ". " + e.getMessage());
        response.setMightHaveMoreResults(true);
    } catch (PersistenceException e) {
        log.info("Requested search query by " + authenticationToken + " failed, possibly due to timeout. "
                + e.getMessage());
        response.setMightHaveMoreResults(true);
    }
    return response;
}

From source file:org.ejbca.core.model.era.RaMasterApiSessionBean.java

@SuppressWarnings("unchecked")
@Override//from   w w  w  . ja v a 2 s. c  om
public RaCertificateSearchResponse searchForCertificates(AuthenticationToken authenticationToken,
        RaCertificateSearchRequest request) {
    final RaCertificateSearchResponse response = new RaCertificateSearchResponse();
    final List<Integer> authorizedLocalCaIds = new ArrayList<>(
            caSession.getAuthorizedCaIds(authenticationToken));
    // Only search a subset of the requested CAs if requested
    if (!request.getCaIds().isEmpty()) {
        authorizedLocalCaIds.retainAll(request.getCaIds());
    }
    final List<String> issuerDns = new ArrayList<>();
    for (final int caId : authorizedLocalCaIds) {
        try {
            final String issuerDn = CertTools
                    .stringToBCDNString(StringTools.strip(caSession.getCAInfoInternal(caId).getSubjectDN()));
            issuerDns.add(issuerDn);
        } catch (CADoesntExistsException e) {
            log.warn("CA went missing during search operation. " + e.getMessage());
        }
    }
    if (issuerDns.isEmpty()) {
        // Empty response since there were no authorized CAs
        if (log.isDebugEnabled()) {
            log.debug("Client '" + authenticationToken
                    + "' was not authorized to any of the requested CAs and the search request will be dropped.");
        }
        return response;
    }
    // Check Certificate Profile authorization
    final List<Integer> authorizedCpIds = new ArrayList<>(
            certificateProfileSession.getAuthorizedCertificateProfileIds(authenticationToken, 0));
    final boolean accessAnyCpAvailable = authorizedCpIds
            .containsAll(certificateProfileSession.getCertificateProfileIdToNameMap().keySet());
    if (!request.getCpIds().isEmpty()) {
        authorizedCpIds.retainAll(request.getCpIds());
    }
    if (authorizedCpIds.isEmpty()) {
        // Empty response since there were no authorized Certificate Profiles
        if (log.isDebugEnabled()) {
            log.debug("Client '" + authenticationToken
                    + "' was not authorized to any of the requested CPs and the search request will be dropped.");
        }
        return response;
    }
    // Check End Entity Profile authorization
    final Collection<Integer> authorizedEepIds = new ArrayList<>(endEntityProfileSession
            .getAuthorizedEndEntityProfileIds(authenticationToken, AccessRulesConstants.VIEW_END_ENTITY));
    final boolean accessAnyEepAvailable = authorizedEepIds
            .containsAll(endEntityProfileSession.getEndEntityProfileIdToNameMap().keySet());
    if (!request.getEepIds().isEmpty()) {
        authorizedEepIds.retainAll(request.getEepIds());
    }
    if (authorizedEepIds.isEmpty()) {
        // Empty response since there were no authorized End Entity Profiles
        if (log.isDebugEnabled()) {
            log.debug("Client '" + authenticationToken
                    + "' was not authorized to any of the requested EEPs and the search request will be dropped.");
        }
        return response;
    }
    final String subjectDnSearchString = request.getSubjectDnSearchString();
    final String subjectAnSearchString = request.getSubjectAnSearchString();
    final String usernameSearchString = request.getUsernameSearchString();
    final String serialNumberSearchStringFromDec = request.getSerialNumberSearchStringFromDec();
    final String serialNumberSearchStringFromHex = request.getSerialNumberSearchStringFromHex();
    final StringBuilder sb = new StringBuilder(
            "SELECT a.fingerprint FROM CertificateData a WHERE (a.issuerDN IN (:issuerDN))");
    if (!subjectDnSearchString.isEmpty() || !subjectAnSearchString.isEmpty() || !usernameSearchString.isEmpty()
            || !serialNumberSearchStringFromDec.isEmpty() || !serialNumberSearchStringFromHex.isEmpty()) {
        sb.append(" AND (");
        boolean firstAppended = false;
        if (!subjectDnSearchString.isEmpty()) {
            sb.append("a.subjectDN LIKE :subjectDN");
            firstAppended = true;
        }
        if (!subjectAnSearchString.isEmpty()) {
            if (firstAppended) {
                sb.append(" OR ");
            } else {
                firstAppended = true;
            }
            sb.append("a.subjectAltName LIKE :subjectAltName");
        }
        if (!usernameSearchString.isEmpty()) {
            if (firstAppended) {
                sb.append(" OR ");
            } else {
                firstAppended = true;
            }
            sb.append("a.username LIKE :username");
        }
        if (!serialNumberSearchStringFromDec.isEmpty()) {
            if (firstAppended) {
                sb.append(" OR ");
            } else {
                firstAppended = true;
            }
            sb.append("a.serialNumber LIKE :serialNumberDec");
        }
        if (!serialNumberSearchStringFromHex.isEmpty()) {
            if (firstAppended) {
                sb.append(" OR ");
            }
            sb.append("a.serialNumber LIKE :serialNumberHex");
        }
        sb.append(")");
    }
    // NOTE: notBefore is not indexed.. we might want to disallow such search.
    if (request.isIssuedAfterUsed()) {
        sb.append(" AND (a.notBefore > :issuedAfter)");
    }
    if (request.isIssuedBeforeUsed()) {
        sb.append(" AND (a.notBefore < :issuedBefore)");
    }
    if (request.isExpiresAfterUsed()) {
        sb.append(" AND (a.expireDate > :expiresAfter)");
    }
    if (request.isExpiresBeforeUsed()) {
        sb.append(" AND (a.expireDate < :expiresBefore)");
    }
    // NOTE: revocationDate is not indexed.. we might want to disallow such search.
    if (request.isRevokedAfterUsed()) {
        sb.append(" AND (a.revocationDate > :revokedAfter)");
    }
    if (request.isRevokedBeforeUsed()) {
        sb.append(" AND (a.revocationDate < :revokedBefore)");
    }
    if (!request.getStatuses().isEmpty()) {
        sb.append(" AND (a.status IN (:status))");
        if ((request.getStatuses().contains(CertificateConstants.CERT_REVOKED)
                || request.getStatuses().contains(CertificateConstants.CERT_ARCHIVED))
                && !request.getRevocationReasons().isEmpty()) {
            sb.append(" AND (a.revocationReason IN (:revocationReason))");
        }
    }
    // Don't constrain results to certain certificate profiles if root access is available and "any" CP is requested
    if (!accessAnyCpAvailable || !request.getCpIds().isEmpty()) {
        sb.append(" AND (a.certificateProfileId IN (:certificateProfileId))");
    }
    // Don't constrain results to certain end entity profiles if root access is available and "any" EEP is requested
    if (!accessAnyEepAvailable || !request.getEepIds().isEmpty()) {
        sb.append(" AND (a.endEntityProfileId IN (:endEntityProfileId))");
    }
    final Query query = entityManager.createQuery(sb.toString());
    query.setParameter("issuerDN", issuerDns);
    if (!accessAnyCpAvailable || !request.getCpIds().isEmpty()) {
        query.setParameter("certificateProfileId", authorizedCpIds);
    }
    if (!accessAnyEepAvailable || !request.getEepIds().isEmpty()) {
        query.setParameter("endEntityProfileId", authorizedEepIds);
    }
    if (log.isDebugEnabled()) {
        log.debug(" issuerDN: " + Arrays.toString(issuerDns.toArray()));
        if (!accessAnyCpAvailable || !request.getCpIds().isEmpty()) {
            log.debug(" certificateProfileId: " + Arrays.toString(authorizedCpIds.toArray()));
        } else {
            log.debug(" certificateProfileId: Any (even deleted) profile(s) due to root access.");
        }
        if (!accessAnyEepAvailable || !request.getEepIds().isEmpty()) {
            log.debug(" endEntityProfileId: " + Arrays.toString(authorizedEepIds.toArray()));
        } else {
            log.debug(" endEntityProfileId: Any (even deleted) profile(s) due to root access.");
        }
    }
    if (!subjectDnSearchString.isEmpty()) {
        if (request.isSubjectDnSearchExact()) {
            query.setParameter("subjectDN", subjectDnSearchString);
        } else {
            query.setParameter("subjectDN", "%" + subjectDnSearchString + "%");
        }
    }
    if (!subjectAnSearchString.isEmpty()) {
        if (request.isSubjectAnSearchExact()) {
            query.setParameter("subjectAltName", subjectAnSearchString);
        } else {
            query.setParameter("subjectAltName", "%" + subjectAnSearchString + "%");
        }
    }
    if (!usernameSearchString.isEmpty()) {
        if (request.isUsernameSearchExact()) {
            query.setParameter("username", usernameSearchString);
        } else {
            query.setParameter("username", "%" + usernameSearchString + "%");
        }
    }
    if (!serialNumberSearchStringFromDec.isEmpty()) {
        query.setParameter("serialNumberDec", serialNumberSearchStringFromDec);
        if (log.isDebugEnabled()) {
            log.debug(" serialNumberDec: " + serialNumberSearchStringFromDec);
        }
    }
    if (!serialNumberSearchStringFromHex.isEmpty()) {
        query.setParameter("serialNumberHex", serialNumberSearchStringFromHex);
        if (log.isDebugEnabled()) {
            log.debug(" serialNumberHex: " + serialNumberSearchStringFromHex);
        }
    }
    if (request.isIssuedAfterUsed()) {
        query.setParameter("issuedAfter", request.getIssuedAfter());
    }
    if (request.isIssuedBeforeUsed()) {
        query.setParameter("issuedBefore", request.getIssuedBefore());
    }
    if (request.isExpiresAfterUsed()) {
        query.setParameter("expiresAfter", request.getExpiresAfter());
    }
    if (request.isExpiresBeforeUsed()) {
        query.setParameter("expiresBefore", request.getExpiresBefore());
    }
    if (request.isRevokedAfterUsed()) {
        query.setParameter("revokedAfter", request.getRevokedAfter());
    }
    if (request.isRevokedBeforeUsed()) {
        query.setParameter("revokedBefore", request.getRevokedBefore());
    }
    if (!request.getStatuses().isEmpty()) {
        query.setParameter("status", request.getStatuses());
        if ((request.getStatuses().contains(CertificateConstants.CERT_REVOKED)
                || request.getStatuses().contains(CertificateConstants.CERT_ARCHIVED))
                && !request.getRevocationReasons().isEmpty()) {
            query.setParameter("revocationReason", request.getRevocationReasons());
        }
    }
    final int maxResults = Math.min(getGlobalCesecoreConfiguration().getMaximumQueryCount(),
            request.getMaxResults());
    query.setMaxResults(maxResults);
    /* Try to use the non-portable hint (depends on DB and JDBC driver) to specify how long in milliseconds the query may run. Possible behaviors:
     * - The hint is ignored
     * - A QueryTimeoutException is thrown
     * - A PersistenceException is thrown (and the transaction which don't have here is marked for roll-back)
     */
    final long queryTimeout = getGlobalCesecoreConfiguration().getMaximumQueryTimeout();
    if (queryTimeout > 0L) {
        query.setHint("javax.persistence.query.timeout", String.valueOf(queryTimeout));
    }
    final List<String> fingerprints;
    try {
        fingerprints = query.getResultList();
        for (final String fingerprint : fingerprints) {
            response.getCdws().add(certificateStoreSession.getCertificateData(fingerprint));
        }
        response.setMightHaveMoreResults(fingerprints.size() == maxResults);
        if (log.isDebugEnabled()) {
            log.debug("Certificate search query: " + sb.toString() + " LIMIT " + maxResults + " \u2192 "
                    + fingerprints.size() + " results. queryTimeout=" + queryTimeout + "ms");
        }
    } catch (QueryTimeoutException e) {
        // Query.toString() does not return the SQL query executed just a java object hash. If Hibernate is being used we can get it using:
        // query.unwrap(org.hibernate.Query.class).getQueryString()
        // We don't have access to hibernate when building this class though, all querying should be moved to the ejbca-entity package.
        // See ECA-5341
        String queryString = e.getQuery().toString();
        //            try {
        //                queryString = e.getQuery().unwrap(org.hibernate.Query.class).getQueryString();
        //            } catch (PersistenceException pe) {
        //                log.debug("Query.unwrap(org.hibernate.Query.class) is not supported by JPA provider");
        //            }
        log.info("Requested search query by " + authenticationToken + " took too long. Query was '"
                + queryString + "'. " + e.getMessage());
        response.setMightHaveMoreResults(true);
    } catch (PersistenceException e) {
        log.info("Requested search query by " + authenticationToken + " failed, possibly due to timeout. "
                + e.getMessage());
        response.setMightHaveMoreResults(true);
    }
    return response;
}