Example usage for org.hibernate Query setTimeout

List of usage examples for org.hibernate Query setTimeout

Introduction

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

Prototype

Query<R> setTimeout(int timeout);

Source Link

Document

Set the query timeout in seconds.

Usage

From source file:aish.vaishno.hibernatesample.FoodOrderDao.java

public Integer deleteFoodOrder(FoodOrder foodOrder) {
    Transaction transaction = session.beginTransaction();
    Query query = session.createQuery("delete FoodOrder where id= :id");
    //  query.setParameter("itemName",foodOrder.getItemName());
    query.setParameter("id", foodOrder.getId());
    query.setTimeout(50);
    Integer result = query.executeUpdate();
    transaction.commit();/*  w w  w .  j  a v a 2 s  .co  m*/
    return result;
}

From source file:com.mysema.query.jpa.hibernate.AbstractHibernateQuery.java

License:Apache License

private Query createQuery(String queryString, @Nullable QueryModifiers modifiers, boolean forCount) {
    Query query = session.createQuery(queryString);
    HibernateUtil.setConstants(query, getConstants(), getMetadata().getParams());
    if (fetchSize > 0) {
        query.setFetchSize(fetchSize);/*from   w  w w  .  ja  v  a  2  s  . c  o m*/
    }
    if (timeout > 0) {
        query.setTimeout(timeout);
    }
    if (cacheable != null) {
        query.setCacheable(cacheable);
    }
    if (cacheRegion != null) {
        query.setCacheRegion(cacheRegion);
    }
    if (comment != null) {
        query.setComment(comment);
    }
    if (readOnly != null) {
        query.setReadOnly(readOnly);
    }
    for (Map.Entry<Path<?>, LockMode> entry : lockModes.entrySet()) {
        query.setLockMode(entry.getKey().toString(), entry.getValue());
    }
    if (flushMode != null) {
        query.setFlushMode(flushMode);
    }

    if (modifiers != null && modifiers.isRestricting()) {
        if (modifiers.getLimit() != null) {
            query.setMaxResults(modifiers.getLimit().intValue());
        }
        if (modifiers.getOffset() != null) {
            query.setFirstResult(modifiers.getOffset().intValue());
        }
    }

    // set transformer, if necessary
    List<? extends Expression<?>> projection = getMetadata().getProjection();
    if (projection.size() == 1 && !forCount) {
        Expression<?> expr = projection.get(0);
        if (expr instanceof FactoryExpression<?>) {
            query.setResultTransformer(
                    new FactoryExpressionTransformer((FactoryExpression<?>) projection.get(0)));
        }
    } else if (!forCount) {
        FactoryExpression<?> proj = FactoryExpressionUtils.wrap(projection);
        if (proj != null) {
            query.setResultTransformer(new FactoryExpressionTransformer(proj));
        }
    }
    return query;
}

From source file:com.querydsl.jpa.hibernate.AbstractHibernateQuery.java

License:Apache License

private Query createQuery(@Nullable QueryModifiers modifiers, boolean forCount) {
    JPQLSerializer serializer = serialize(forCount);
    String queryString = serializer.toString();
    logQuery(queryString, serializer.getConstantToLabel());
    Query query = session.createQuery(queryString);
    HibernateUtil.setConstants(query, serializer.getConstantToLabel(), getMetadata().getParams());
    if (fetchSize > 0) {
        query.setFetchSize(fetchSize);/*from  w  ww .j  a  va  2 s .  co  m*/
    }
    if (timeout > 0) {
        query.setTimeout(timeout);
    }
    if (cacheable != null) {
        query.setCacheable(cacheable);
    }
    if (cacheRegion != null) {
        query.setCacheRegion(cacheRegion);
    }
    if (comment != null) {
        query.setComment(comment);
    }
    if (readOnly != null) {
        query.setReadOnly(readOnly);
    }
    for (Map.Entry<Path<?>, LockMode> entry : lockModes.entrySet()) {
        query.setLockMode(entry.getKey().toString(), entry.getValue());
    }
    if (flushMode != null) {
        query.setFlushMode(flushMode);
    }

    if (modifiers != null && modifiers.isRestricting()) {
        Integer limit = modifiers.getLimitAsInteger();
        Integer offset = modifiers.getOffsetAsInteger();
        if (limit != null) {
            query.setMaxResults(limit);
        }
        if (offset != null) {
            query.setFirstResult(offset);
        }
    }

    // set transformer, if necessary
    Expression<?> projection = getMetadata().getProjection();
    if (!forCount && projection instanceof FactoryExpression) {
        query.setResultTransformer(new FactoryExpressionTransformer((FactoryExpression<?>) projection));
    }
    return query;
}

From source file:lucee.runtime.orm.hibernate.HibernateORMSession.java

License:Open Source License

private Object __executeQuery(PageContext pc, Session session, Key dsn, String hql, Object params,
        boolean unique, Struct options) throws PageException {
    //Session session = getSession(pc,null);
    hql = hql.trim();/*from   w  ww  .j  av a2s  .  c o m*/
    org.hibernate.Query query = session.createQuery(hql);
    // options
    if (options != null) {
        // maxresults
        Object obj = options.get("maxresults", null);
        if (obj != null) {
            int max = CommonUtil.toIntValue(obj, -1);
            if (max < 0)
                throw ExceptionUtil.createException(this, null, "option [maxresults] has an invalid value ["
                        + obj + "], value should be a number bigger or equal to 0", null);
            query.setMaxResults(max);
        }
        // offset
        obj = options.get("offset", null);
        if (obj != null) {
            int off = CommonUtil.toIntValue(obj, -1);
            if (off < 0)
                throw ExceptionUtil.createException(this, null, "option [offset] has an invalid value [" + obj
                        + "], value should be a number bigger or equal to 0", null);
            query.setFirstResult(off);
        }
        // readonly
        obj = options.get("readonly", null);
        if (obj != null) {
            Boolean ro = CommonUtil.toBoolean(obj, null);
            if (ro == null)
                throw ExceptionUtil.createException(this, null,
                        "option [readonly] has an invalid value [" + obj + "], value should be a boolean value",
                        null);
            query.setReadOnly(ro.booleanValue());
        }
        // timeout
        obj = options.get("timeout", null);
        if (obj != null) {
            int to = CommonUtil.toIntValue(obj, -1);
            if (to < 0)
                throw ExceptionUtil.createException(this, null, "option [timeout] has an invalid value [" + obj
                        + "], value should be a number bigger or equal to 0", null);
            query.setTimeout(to);
        }
    }

    // params
    if (params != null) {
        QueryPlanCache cache = data.getQueryPlanCache(dsn);
        HQLQueryPlan plan = cache.getHQLQueryPlan(hql, false, java.util.Collections.EMPTY_MAP);
        ParameterMetadata meta = plan.getParameterMetadata();
        Type type;
        Object obj;

        // struct
        if (CommonUtil.isStruct(params)) {
            Struct sct = CommonUtil.toStruct(params);
            Key[] keys = CommonUtil.keys(sct);
            String name;
            // fix case-senstive
            Struct names = CommonUtil.createStruct();
            if (meta != null) {
                Iterator<String> it = meta.getNamedParameterNames().iterator();
                while (it.hasNext()) {
                    name = it.next();
                    names.setEL(name, name);
                }
            }

            RefBoolean isArray = CommonUtil.createRefBoolean();
            for (int i = 0; i < keys.length; i++) {
                obj = sct.get(keys[i], null);
                if (meta != null) {
                    name = (String) names.get(keys[i], null);
                    if (name == null)
                        continue; // param not needed will be ignored
                    type = meta.getNamedParameterExpectedType(name);
                    obj = HibernateCaster.toSQL(type, obj, isArray);
                    if (isArray.toBooleanValue()) {
                        if (obj instanceof Object[])
                            query.setParameterList(name, (Object[]) obj, type);
                        else if (obj instanceof List)
                            query.setParameterList(name, (List) obj, type);
                        else
                            query.setParameterList(name, Caster.toList(obj), type);
                    } else
                        query.setParameter(name, obj, type);

                } else
                    query.setParameter(keys[i].getString(), obj);
            }
        }

        // array
        else if (CommonUtil.isArray(params)) {
            Array arr = CommonUtil.toArray(params);
            Iterator it = arr.valueIterator();
            int index = 0;
            SQLItem item;
            RefBoolean isArray = null;
            while (it.hasNext()) {
                obj = it.next();
                if (obj instanceof SQLItem) {
                    item = (SQLItem) obj;
                    obj = item.getValue();
                    //HibernateCaster.toHibernateType(item.getType(), null); MUST
                    //query.setParameter(index, item.getValue(),type);
                }
                if (meta != null) {
                    type = meta.getOrdinalParameterExpectedType(index + 1);
                    obj = HibernateCaster.toSQL(type, obj, isArray);
                    // TOOD can the following be done somehow
                    //if(isArray.toBooleanValue())
                    //   query.setParameterList(index, (Object[])obj,type);
                    //else
                    query.setParameter(index, obj, type);
                } else
                    query.setParameter(index, obj);
                index++;
            }
            if (meta.getOrdinalParameterCount() > index)
                throw ExceptionUtil.createException(this, null, "parameter array is to small [" + arr.size()
                        + "], need [" + meta.getOrdinalParameterCount() + "] elements", null);
        }
    }

    // select
    String lcHQL = hql.toLowerCase();
    if (lcHQL.startsWith("select") || lcHQL.startsWith("from")) {
        if (unique) {
            return uniqueResult(query);
        }

        return query.list();
    }
    // update
    return new Double(query.executeUpdate());
}

From source file:org.grails.orm.hibernate.GrailsHibernateTemplate.java

License:Apache License

/**
 * Prepare the given Query object, applying cache settings and/or a
 * transaction timeout./*from ww  w.  j a  v a 2 s.c o  m*/
 *
 * @param query the Query object to prepare
 */
protected void prepareQuery(Query query) {
    if (cacheQueries) {
        query.setCacheable(true);
    }
    if (shouldPassReadOnlyToHibernate()) {
        query.setReadOnly(true);
    }
    SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
    if (sessionHolder != null && sessionHolder.hasTimeout()) {
        query.setTimeout(sessionHolder.getTimeToLiveInSeconds());
    }
}

From source file:org.openbravo.service.db.QueryTimeOutUtil.java

License:Open Source License

/**
 * Sets a timeout for a hibernate query, if possible
 * //from   w w  w .j  a  v a2s  .c  om
 * @param query
 * @param type
 *          query type, it will be used to fetch the proper timeout
 * 
 */
public void setQueryTimeOut(Query query, String type) {
    if (canApplyTimeOut && checkQueryType(type)) {
        query.setTimeout(queryTimeOutMap.get(type));
    }
}

From source file:org.openbravo.service.db.QueryTimeOutUtil.java

License:Open Source License

/**
 * Sets the 0 the timeout of a hibernate query
 *//* w w  w. ja  v a 2s. c  om*/
public static void resetQueryTimeOut(Query query) {
    query.setTimeout(0);
}

From source file:org.pentaho.platform.plugin.services.connections.hql.HQLConnection.java

License:Open Source License

public IPentahoResultSet executeQuery(final String query) {
    lastQuery = query;/* w  ww. j a  v a 2 s  .  c  o m*/
    Session sess = null;
    IPentahoResultSet localResultSet = null;
    try {
        SessionFactory sf = hibernateConfig.buildSessionFactory();
        // open session
        sess = sf.openSession();
        Query q = sess.createQuery(query);
        if (timeOut >= 0) {
            q.setTimeout(timeOut);
        }
        if (maxRows >= 0) {
            q.setMaxResults(maxRows);
        }
        List list = q.list();
        localResultSet = generateResultSet(list, q.getReturnAliases(), q.getReturnTypes());
    } finally {
        try {
            if (sess != null) {
                sess.close();
            }
        } catch (Exception e) {
            // Doesn't seem like we would get any exception from sess.close()
            logger.error(Messages.getInstance().getErrorString("HQLConnection.ERROR_0001_UNABLE_TO_CLOSE"), e); //$NON-NLS-1$
        }
    }

    return localResultSet;
}

From source file:org.pentaho.reporting.engine.classic.extensions.datasources.hibernate.SimpleHQLDataFactory.java

License:Open Source License

/**
 * Queries a datasource. The string 'query' defines the name of the query. The Parameterset given here may contain
 * more data than actually needed./*  w w  w.  j  a  v a2  s . c o m*/
 * <p/>
 * The dataset may change between two calls, do not assume anything!
 *
 * @param query
 * @param parameters
 * @return
 */
public synchronized TableModel queryData(final String query, final DataRow parameters)
        throws ReportDataFactoryException {
    try {
        final Query pstmt = getSession().createQuery(query);
        final String[] params = pstmt.getNamedParameters();
        for (int i = 0; i < params.length; i++) {
            final String param = params[i];
            final Object pvalue = parameters.get(param);
            if (pvalue == null) {
                // this should work, but some driver are known to die here.
                // they should be fed with setNull(..) instead; something
                // we cant do as JDK1.2's JDBC does not define it.
                pstmt.setParameter(param, null);
            } else {
                pstmt.setParameter(param, pvalue);
            }
        }

        final Object queryLimit = parameters.get(DataFactory.QUERY_LIMIT);
        if (queryLimit instanceof Number) {
            final Number i = (Number) queryLimit;
            if (i.intValue() >= 0) {
                pstmt.setMaxResults(i.intValue());
            }
        }
        final Object queryTimeout = parameters.get(DataFactory.QUERY_TIMEOUT);
        if (queryTimeout instanceof Number) {
            final Number i = (Number) queryLimit;
            if (i.intValue() >= 0) {
                pstmt.setTimeout(i.intValue());
            }
        }
        final ScrollableResults res = pstmt.scroll(ScrollMode.FORWARD_ONLY);
        return generateDefaultTableModel(res, pstmt.getReturnAliases());
    } catch (Exception e) {
        throw new ReportDataFactoryException("Failed at query: " + query, e);
    }
}

From source file:org.rhq.server.metrics.migrator.datasources.ScrollableDataSource.java

License:Open Source License

@Override
public void initialize() {
    if (session != null || results != null) {
        close();/*from  w ww .j ava2 s .c  o  m*/
    }

    session = ((Session) entityManager.getDelegate()).getSessionFactory().openStatelessSession();

    this.prepareSQLSession();

    if (log.isDebugEnabled()) {
        if (maxResults >= 0) {
            log.debug("Preparing the query with " + maxResults + " results.");
        } else {
            log.debug("Preparing the query with all the results.");
        }
    }

    Query query = session.createSQLQuery(selectNativeQuery);
    if (maxResults >= 0) {
        query.setMaxResults(maxResults);
    }
    query.setFetchSize(30000);
    query.setReadOnly(true);
    query.setTimeout(TIMEOUT);
    results = query.scroll(ScrollMode.FORWARD_ONLY);

    lastMigratedItemIndex = -1;

    if (log.isDebugEnabled()) {
        if (maxResults >= 0) {
            log.debug("Query prepared with " + maxResults + " results.");
        } else {
            log.debug("Query prepared with all the results.");
        }
    }
}