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:org.easy.criteria.QueryProperties.java

public void applyProperties(Query query) {
    if (flashMode != null) {
        log.debug("flashMode = " + flashMode);
        query.setFlushMode(flashMode);//ww  w. ja v  a 2 s  . c o m
    }

    if (lockMode != null) {
        log.debug("lockMode = " + lockMode);
        query.setLockMode(lockMode);
    }

    if (hintKey != null) {
        log.debug("hintKey = " + hintKey);
        log.debug("hintValue = " + hintValue);
        query.setHint(hintKey, hintValue);
    }

    if (startIndex >= 0 && maxResult > 0) {
        log.debug("startIndex = " + startIndex * maxResult);
        query.setFirstResult(startIndex * maxResult);
    }

    if (maxResult > 0) {
        log.debug("maxResult = " + maxResult);
        query.setMaxResults(maxResult);
    }
}

From source file:org.broadleafcommerce.core.order.dao.OrderDaoImpl.java

@Override
public boolean acquireLock(Order order) {
    String orderLockKey = getOrderLockKey();
    // First, we'll see if there's a record of a lock for this order
    Query q = em.createNamedQuery("BC_ORDER_LOCK_READ");
    q.setParameter("orderId", order.getId());
    q.setParameter("key", orderLockKey);
    q.setHint(QueryHints.HINT_CACHEABLE, false);
    Long count = (Long) q.getSingleResult();

    if (count == 0L) {
        // If there wasn't a lock, we'll try to create one. It's possible that another thread is attempting the
        // same thing at the same time, so we might get a constraint violation exception here. That's ok. If we 
        // successfully inserted a record, that means that we are the owner of the lock right now.
        try {/*from  w w  w. ja va2 s.  c  o  m*/
            OrderLock ol = (OrderLock) entityConfiguration.createEntityInstance(OrderLock.class.getName());
            ol.setOrderId(order.getId());
            ol.setLocked(true);
            ol.setKey(orderLockKey);
            ol.setLastUpdated(System.currentTimeMillis());
            em.persist(ol);
            return true;
        } catch (EntityExistsException e) {
            return false;
        }
    }

    // We weren't successful in creating a lock, which means that there was some previously created lock
    // for this order. We'll attempt to update the status from unlocked to locked. If that is successful,
    // we acquired the lock. 
    q = em.createNamedQuery("BC_ORDER_LOCK_ACQUIRE");
    q.setParameter("orderId", order.getId());
    q.setParameter("currentTime", System.currentTimeMillis());
    q.setParameter("key", orderLockKey);
    Long orderLockTimeToLive = getDatabaseOrderLockTimeToLive();
    q.setParameter("timeout", orderLockTimeToLive == -1L ? orderLockTimeToLive
            : System.currentTimeMillis() - orderLockTimeToLive);
    q.setHint(QueryHints.HINT_CACHEABLE, false);
    int rowsAffected = q.executeUpdate();

    return rowsAffected == 1;
}

From source file:org.apache.ranger.common.RangerSearchUtil.java

public void updateQueryPageSize(Query query, SearchFilter searchCriteria) {
    int pageSize = super.validatePageSize(searchCriteria.getMaxRows());
    query.setMaxResults(pageSize);/*from  ww w .j a va2 s  . com*/

    query.setHint("eclipselink.jdbc.max-rows", "" + pageSize);
}

From source file:com.hiperium.dao.common.generic.GenericDAO.java

/**
 * /*from   ww  w .  ja  v a  2s .  c  o m*/
 * @param query
 */
private void setBypassCahe(Query query) {
    query.setHint(RETRIEVE_MODE, CacheRetrieveMode.BYPASS);
    query.setHint(STORE_MODE, CacheStoreMode.REFRESH);
}

From source file:org.broadleafcommerce.core.order.dao.OrderDaoImpl.java

@Override
public boolean releaseLock(final Order order) {
    final boolean[] response = { false };
    try {//w  w  w . j av  a 2s  . c  om
        transUtil.runTransactionalOperation(new StreamCapableTransactionalOperationAdapter() {
            @Override
            public void execute() throws Throwable {
                Query q = em.createNamedQuery("BC_ORDER_LOCK_RELEASE");
                q.setParameter("orderId", order.getId());
                q.setParameter("key", getOrderLockKey());
                q.setHint(QueryHints.HINT_CACHEABLE, false);
                int rowsAffected = q.executeUpdate();
                response[0] = rowsAffected == 1;
            }

            @Override
            public boolean shouldRetryOnTransactionLockAcquisitionFailure() {
                return true;
            }
        }, RuntimeException.class);
    } catch (RuntimeException e) {
        LOG.error(String.format("Could not release order lock (%s)", order.getId()), e);
    }
    return response[0];
}

From source file:se.vgregion.webbisar.svc.impl.WebbisDaoHibernate.java

/**
 * {@inheritDoc}/*  w w w .  jav a  2s. com*/
 */
@SuppressWarnings("unchecked")
public List<Webbis> getWebbisarForAuthorId(final String authorId) {
    Object results = getJpaTemplate().execute(new JpaCallback() {
        public Object doInJpa(EntityManager em) throws PersistenceException {
            Query q = em.createQuery(
                    "SELECT w FROM Webbis w WHERE w.authorId = :author AND w.disabled = false AND w.multipleBirthMainWebbis IS NULL");
            q.setParameter("author", authorId);
            q.setHint("org.hibernate.cacheable", true);
            return q.getResultList();
        }
    });
    return (List<Webbis>) results;
}

From source file:org.broadleafcommerce.core.order.dao.OrderDaoImpl.java

@Override
public Order readCartForCustomer(final Customer customer) {
    Order order = null;//from   w w w. j  a v a 2  s. co m
    final Query query = em.createNamedQuery("BC_READ_ORDERS_BY_CUSTOMER_ID_AND_NAME_NULL");
    query.setParameter("customerId", customer.getId());
    query.setParameter("orderStatus", OrderStatus.IN_PROCESS.getType());
    query.setHint(QueryHints.HINT_CACHEABLE, true);
    query.setHint(QueryHints.HINT_CACHE_REGION, "query.Order");
    @SuppressWarnings("rawtypes")
    final List temp = query.getResultList();
    if (temp != null && !temp.isEmpty()) {
        order = (Order) temp.get(0);
    }
    return order;
}

From source file:org.codehaus.grepo.query.jpa.generator.QueryGeneratorBase.java

protected void applyAddHintsSetting(JpaQueryOptions queryOptions, Query query,
        JpaQueryExecutionContext context) {
    if (!CollectionUtils.isEmpty(context.getDefaultQueryHints())) {
        for (Entry<String, Object> entry : context.getDefaultQueryHints().entrySet()) {
            query.setHint(entry.getKey(), entry.getValue());
            logger.debug("Setting default hint name={} value={}", entry.getKey(), entry.getValue());
        }//from   w  ww. j av  a2 s .  com
    }
    if (queryOptions != null) {
        for (QueryHint hint : queryOptions.queryHints()) {
            query.setHint(hint.name(), hint.value());
            logger.debug("Setting hint name={} value={}", hint.name(), hint.value());
        }
    }
    if (hasHints()) {
        for (Entry<String, Object> entry : hints.entrySet()) {
            query.setHint(entry.getKey(), entry.getValue());
            logger.debug("Setting hint name={} value={}", entry.getKey(), entry.getValue());
        }
    }
}

From source file:com.healthcit.cacure.dao.FormElementDao.java

/**
 * @param formId Long//  w ww  .  ja  v  a2 s.  c o  m
 * @return List<Question> ordered by ord that fetches list of answers and skipPatterns
 */
@SuppressWarnings("unchecked")
public List<FormElement> getAllFormElements(Long formId) {
    Query query = em.createQuery(
            "select q from FormElement q left join fetch q.skipRule where q.form.id = :formId order by q.ord");
    query.setHint("org.hibernate.cacheable", true);
    query.setParameter("formId", formId);

    List<FormElement> elements = (List<FormElement>) query.getResultList();

    // Notice empty statement in order to start each subselect
    /*
            for (FormElement e : elements) {
               if (e instanceof QuestionElement) 
               {
      ((QuestionElement)e).getQuestion();
               }
               if (e instanceof ExternalQuestionElement) 
               {
      ((ExternalQuestionElement)e).getQuestion();
               }
               else if (e instanceof TableElement)
               {
      for (@SuppressWarnings("unused") BaseQuestion question: ((TableElement)e).getQuestions())
      {
         break; // just to load it
      }
               }
               FormElementSkipRule rule = e.getSkipRule();
               if (rule != null)
               {
      for (@SuppressWarnings("unused") QuestionSkipRule sp: rule.getQuestionSkipRules())
      {
         break; // just to load it
      }
               }
               //Why is there a break after the first question?
      //          break;
            }
    */
    return elements;
}

From source file:org.opentides.dao.impl.BaseEntityDaoJpaImpl.java

private void setHints(T obj, Query query) {
    if (obj.getHints() != null) {
        for (String hint : obj.getHints().keySet()) {
            query.setHint(hint, obj.getHints().get(hint));
        }//  w  w  w .j  a v  a 2 s .  co m
    }
}