Java Code Examples for javax.persistence.Query#setHint()

The following examples show how to use javax.persistence.Query#setHint() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RepositoryQueryEntityGraphInjector.java    From spring-data-jpa-entity-graph with MIT License 6 votes vote down vote up
private void addEntityGraphToQuery(Query query) {
  if (CountQueryDetector.isCountQuery()) {
    LOG.trace("CountQuery detected.");
    return;
  }
  if (!entityGraphCandidate.isPrimary()
      && QueryHintsUtils.containsEntityGraph(query.getHints())) {
    LOG.trace(
        "The query hints passed with the find method already hold an entity graph. Overriding aborted because the candidate EntityGraph is optional.");
    return;
  }

  QueryHintsUtils.removeEntityGraphs(query.getHints());
  Map<String, Object> hints =
      QueryHintsUtils.buildQueryHints(entityManager, entityGraphCandidate);
  for (Map.Entry<String, Object> hint : hints.entrySet()) {
    query.setHint(hint.getKey(), hint.getValue());
  }
}
 
Example 2
Source File: CommonDAOSpringImpl.java    From EasyEE with MIT License 6 votes vote down vote up
/**
 * CommonDAO 内部方法,NamedQuery
 * 
 * @param entityManager
 *            entityManager
 * @param name
 *            name
 * @param cacheable
 *            cacheable
 * @param cacheRegion
 *            cacheRegion
 * @param values
 *            values
 * @return Query对象
 */
private Query createNamedQuery(EntityManager entityManager, String name, boolean cacheable, String cacheRegion,
		Map<String, Object> values) {
	Query query = entityManager.createNamedQuery(name.trim());
	if (cacheable) {
		query.setHint(QueryHints.HINT_CACHEABLE, "true");
		if (cacheRegion != null && (!cacheRegion.equals(""))) {
			query.setHint(QueryHints.HINT_CACHE_REGION, cacheRegion);
		}
	}
	if (values != null && values.size() > 0) {
		for (Entry<String, Object> e : values.entrySet()) {
			query.setParameter(e.getKey(), e.getValue());
		}
	}
	return query;
}
 
Example 3
Source File: DatabaseHelper.java    From desktop with GNU General Public License v3.0 6 votes vote down vote up
public CloneFile getWorkspaceRoot(String id) {
    CloneFile workspaceRoot;
    
    String queryStr = "select cf from CloneFile cf where "
            + "        cf.workspaceRoot = :isRoot and"
            + "        cf.version = ("
            + "            select max(cf2.version) from CloneFile cf2 where cf.id = cf2.id) and "
            + "        cf.workspace = ("
            + "           select wp from CloneWorkspace wp where "
            + "           wp.id = :workspaceId"
            + "        )";

    Query query = config.getDatabase().getEntityManager().createQuery(queryStr, CloneChunk.class);
    query.setHint("javax.persistence.cache.storeMode", "REFRESH");
    query.setHint("eclipselink.cache-usage", "DoNotCheckCache");
    query.setParameter("isRoot", true);
    query.setParameter("workspaceId", id);

    workspaceRoot = (CloneFile) query.getSingleResult();
    
    return workspaceRoot;
}
 
Example 4
Source File: getFidoKeys.java    From fido2 with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 *
 * @param did
 * @param username - Name of the user whose keys need to be fetched.
 * @param status - status of Fido key (Active vs Inactive)
 * @return - List of keys for the supplied username
 */
@Override
public FidoKeys getNewestKeyByUsernameStatus(Long did, String username, String status) throws SKFEException {
    try {
        Query q = em.createNamedQuery("FidoKeys.findNewestKeyByUsernameStatus", FidoKeys.class);
        q.setHint("javax.persistence.cache.storeMode", "REFRESH");
        q.setParameter("username", username);
        q.setParameter("did", did);
        q.setParameter("status", status);

        List<FidoKeys> fkList = q.getResultList();
        if (fkList == null || fkList.isEmpty()) {
            return null;
        }
        FidoKeys rk = fkList.get(0);
        if (rk != null) {
            verifyDBRecordSignature(did, rk);
        }
        return rk;
    } catch (NoResultException ex) {
        return null;
    }
}
 
Example 5
Source File: OfferEndpoint.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * This method lists all the entities inserted in datastore.
 * It uses HTTP GET method and paging support.
 *
 * @return A CollectionResponse class containing the list of all entities
 * persisted and a cursor to the next page.
 */
@SuppressWarnings({"unchecked", "unused"})
@ApiMethod(name = "listOffer")
public CollectionResponse<Offer> listOffer(
    @Nullable @Named("cursor") String cursorString, @Nullable @Named("limit") Integer limit) {

  EntityManager mgr = null;
  Cursor cursor = null;
  List<Offer> execute = null;

  try {
    mgr = getEntityManager();
    Query query = mgr.createQuery("select from Offer as Offer");
    if (cursorString != null && cursorString != "") {
      cursor = Cursor.fromWebSafeString(cursorString);
      query.setHint(JPACursorHelper.CURSOR_HINT, cursor);
    }

    if (limit != null) {
      query.setFirstResult(0);
      query.setMaxResults(limit);
    }

    execute = (List<Offer>) query.getResultList();
    cursor = JPACursorHelper.getCursor(execute);
    if (cursor != null) cursorString = cursor.toWebSafeString();

    // Tight loop for fetching all entities from datastore and accomodate
    // for lazy fetch.
    for (Offer obj : execute);
  } finally {
    mgr.close();
  }

  return CollectionResponse.<Offer>builder()
      .setItems(execute).setNextPageToken(cursorString).build();
}
 
Example 6
Source File: ActDAOImpl.java    From Asqatasun with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Act findLastActByContractAndScenario(Long idContract, String scenarioName) {
    StringBuilder queryString = new StringBuilder();
    queryString.append("SELECT a FROM ");
    queryString.append(ActImpl.class.getName());
    queryString.append(" a");
    queryString.append(" left join a.audit.subject w");
    queryString.append(" WHERE a.contract.id = :idContract");
    queryString.append(" AND (a.status = :completedStatus OR a.status = :errorStatus)");
    queryString.append(" AND a.scope.code =:scope ");
    queryString.append(" AND w.url=:scenarioName");
    queryString.append(" ORDER BY a.id DESC");
    
    Query query = entityManager.createQuery(queryString.toString());
    query.setParameter("idContract", idContract);
    query.setParameter("completedStatus", ActStatus.COMPLETED);
    query.setParameter("errorStatus", ActStatus.ERROR);
    query.setParameter("scope", ScopeEnum.SCENARIO);
    query.setParameter("scenarioName", scenarioName);
    query.setMaxResults(1);
    query.setHint(CACHEABLE_OPTION, "true");
    try {
        return (Act)query.getSingleResult();
    } catch (NoResultException nre) {
        return null;
    }
}
 
Example 7
Source File: WebResourceDAOImpl.java    From Asqatasun with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public WebResource ligthRead(Long webResourceId) {
    try {
        Query query = entityManager.createQuery("SELECT wr FROM "
                + getEntityClass().getName() + " wr"
                + " WHERE wr.id = :id");
        query.setParameter("id", webResourceId);
        query.setHint(CACHEABLE_OPTION, TRUE);
        return (WebResource) query.getSingleResult();
    } catch (NoResultException nre) {
        return null;
    }
}
 
Example 8
Source File: TestDAOImpl.java    From Asqatasun with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public List<Test> retrieveAllByCriterion(Criterion criterion) {
    StringBuilder queryStr = new StringBuilder();
    queryStr.append("SELECT t FROM ");
    queryStr.append(getEntityClass().getName());
    queryStr.append(" t WHERE");
    queryStr.append(" t.criterion = :criterion");
    Query query = entityManager.createQuery(queryStr.toString());
    query.setParameter("criterion", criterion);
    query.setHint("org.hibernate.cacheable", "true");
    return query.getResultList();
}
 
Example 9
Source File: PlaceEndpoint.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * This method lists all the entities inserted in datastore.
 * It uses HTTP GET method and paging support.
 *
 * @return A CollectionResponse class containing the list of all entities
 * persisted and a cursor to the next page.
 */
@SuppressWarnings({"unchecked", "unused"})
@ApiMethod(name = "listPlace")
public CollectionResponse<Place> listPlace(
    @Nullable @Named("cursor") String cursorString, @Nullable @Named("limit") Integer limit) {

  EntityManager mgr = null;
  Cursor cursor = null;
  List<Place> execute = null;

  try {
    mgr = getEntityManager();
    Query query = mgr.createQuery("select from Place as Place");
    if (cursorString != null && cursorString != "") {
      cursor = Cursor.fromWebSafeString(cursorString);
      query.setHint(JPACursorHelper.CURSOR_HINT, cursor);
    }

    if (limit != null) {
      query.setFirstResult(0);
      query.setMaxResults(limit);
    }

    execute = (List<Place>) query.getResultList();
    cursor = JPACursorHelper.getCursor(execute);
    if (cursor != null) cursorString = cursor.toWebSafeString();

    // Tight loop for fetching all entities from datastore and accomodate
    // for lazy fetch.
    for (Place obj : execute);
  } finally {
    mgr.close();
  }

  return CollectionResponse.<Place>builder()
      .setItems(execute).setNextPageToken(cursorString).build();
}
 
Example 10
Source File: TestQueryCaching.java    From Hands-On-High-Performance-with-Spring-5 with MIT License 5 votes vote down vote up
@Transactional
private void queryCache(){
	_logger.warn("Query Cache");
	Query query = entityManager.createQuery("SELECT a FROM Account a WHERE a.accountId=:accountId", Account.class);
	query.setParameter("accountId", 7L);
	query.setHint("org.hibernate.cacheable", true);
	Account account = (Account)query.getSingleResult();
	_logger.warn(account);
}
 
Example 11
Source File: ActDAOImpl.java    From Asqatasun with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Collection<Act> findAllActsByContract(Contract contract) {
    Query query = entityManager.createQuery("SELECT a FROM "
            + getEntityClass().getName() + " a"
            + " WHERE a.contract = :contract");
    query.setHint(CACHEABLE_OPTION, "true");
    query.setParameter("contract", contract);
    return (List<Act>)query.getResultList();
}
 
Example 12
Source File: DatabaseHelper.java    From desktop with GNU General Public License v3.0 5 votes vote down vote up
public Map<String, List<CloneFile>> getHistoryUptoDate() {
    Calendar cal = Calendar.getInstance();  
    cal.set(getFieldTimeout(), getValueTimeout(cal)); 
    Date time = cal.getTime();        
    
    String queryStr = "select c from CloneFile c where "
            + "     c.syncStatus = :statusSync and "                
            + "     c.serverUploadedAck = false and "
            + "     c.workspaceRoot = false and "
            + "     (c.serverUploadedTime < :timeNow or "
            + "     c.serverUploadedTime is null) order by "
            + "                                     c.path asc, c.version asc";    
    
    Query query = config.getDatabase().getEntityManager().createQuery(queryStr, CloneFile.class);
    query.setHint("javax.persistence.cache.storeMode", "REFRESH");
    query.setHint("eclipselink.cache-usage", "DoNotCheckCache");        
    
    query.setParameter("statusSync", CloneFile.SyncStatus.UPTODATE);       
    query.setParameter("timeNow", time);
    
    Map<String, List<CloneFile>> workspaces = new HashMap<String, List<CloneFile>>();
    List<CloneFile> clonefiles = query.getResultList();
    for(CloneFile cf: clonefiles){
        if(!workspaces.containsKey(cf.getWorkspace().getId())){
            workspaces.put(cf.getWorkspace().getId(), new ArrayList<CloneFile>());
        } 
            
        workspaces.get(cf.getWorkspace().getId()).add(cf);            
    }
    
    return workspaces;
}
 
Example 13
Source File: ByNamedQueryUtil.java    From javaee-lab with Apache License 2.0 5 votes vote down vote up
private Query recreateQuery(Query current, String newSqlString) {
    Query result = entityManager.createQuery(newSqlString);
    for (Entry<String, Object> hint : current.getHints().entrySet()) {
        result.setHint(hint.getKey(), hint.getValue());
    }
    return result;
}
 
Example 14
Source File: DatabaseHelper.java    From desktop with GNU General Public License v3.0 5 votes vote down vote up
public CloneWorkspace getWorkspace(String id) {
    String queryStr = "select w from CloneWorkspace w where"
            + "            w.id = :id";        
    Query query = config.getDatabase().getEntityManager().createQuery(queryStr, CloneWorkspace.class);
    query.setHint("javax.persistence.cache.storeMode", "REFRESH");
    query.setHint("eclipselink.cache-usage", "DoNotCheckCache");        
    
    query.setParameter("id", id);
    CloneWorkspace workspace = (CloneWorkspace)query.getSingleResult();
    
    return workspace;
}
 
Example 15
Source File: Database.java    From desktop with GNU General Public License v3.0 5 votes vote down vote up
public synchronized Query createQuery(String query, Class type) {
    Query request = getEntityManager().createQuery(query, type);

    request.setHint("javax.persistence.cache.storeMode", "REFRESH");
    request.setHint("eclipselink.cache-usage", "DoNotCheckCache");

    return request;
}
 
Example 16
Source File: AbstractQueryExecutorImpl.java    From katharsis-framework with Apache License 2.0 5 votes vote down vote up
protected void applyFetchPaths(Query criteriaQuery) {
	EntityGraph<T> graph = em.createEntityGraph(getEntityClass());
	for (MetaAttributePath fetchPath : fetchPaths) {
		applyFetchPaths(graph, fetchPath);
	}
	criteriaQuery.setHint("javax.persistence.fetchgraph", graph);
}
 
Example 17
Source File: TestDAOImpl.java    From Asqatasun with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public List<Test> retrieveAll(Reference reference) {
    Query query = entityManager.createQuery("SELECT t FROM "
            + getEntityClass().getName() + " t"
            + " WHERE t.criterion.reference = :reference");
    query.setParameter("reference", reference);
    query.setHint("org.hibernate.cacheable", "true");
    return (List<Test>) query.getResultList();
}
 
Example 18
Source File: RepositoryHelper.java    From es with Apache License 2.0 4 votes vote down vote up
public void applyEnableQueryCache(Query query) {
    if (enableQueryCache) {
        query.setHint("org.hibernate.cacheable", true);//开启查询缓存
    }
}
 
Example 19
Source File: BaseObject.java    From activejpa with Apache License 2.0 4 votes vote down vote up
private static void updateQueryParams(Query query, Filter filter) {
	filter.setParameters(query);
	filter.setPage(query);
	query.setHint(JPA.instance.getCacheableHint(), filter.isCacheable());
}
 
Example 20
Source File: SearchUtil.java    From ranger with Apache License 2.0 3 votes vote down vote up
public void updateQueryPageSize(Query query, SearchCriteria searchCriteria) {
	// Set max records
	int pageSize = validatePageSize(searchCriteria.getMaxRows());

	query.setMaxResults(pageSize);

	// Set hint for max records
	query.setHint("eclipselink.jdbc.max-rows", "" + pageSize);

}