List of usage examples for javax.persistence Query setFirstResult
Query setFirstResult(int startPosition);
From source file:ca.travelagency.persistence.query.QuerySQL.java
public static QuerySQL find(Criteria criteria, EntityManager entityManager) { return new QuerySQL(criteria, entityManager) { @Override/*from ww w .j a va2 s . co m*/ protected String sqlAsString() { return SELECT + DISTINCT + simpleName + from() + where() + orderBy(); } @Override protected void addLimits(Query query) { if (criteria.getCount() != 0) { // FIXME JPA Query uses int we use long query.setFirstResult((int) criteria.getOffset()); query.setMaxResults((int) criteria.getCount()); } } }; }
From source file:com.siberhus.ngai.core.CrudHelper.java
@SuppressWarnings("unchecked") public final static List<Object> findByQTO(EntityManager em, QTO qto) { Query query = createQueryObject(em, qto.buildQueryString(), qto.getParameterList()); if (qto.getFirstResult() != null) { query.setFirstResult(qto.getFirstResult()); }// www . ja v a 2 s .c o m if (qto.getMaxResult() != null) { query.setMaxResults(qto.getMaxResult()); } return query.getResultList(); }
From source file:org.querybyexample.jpa.JpaUtil.java
public static void applyPagination(Query query, SearchParameters sp) { if (sp.getFirst() > 0) { query.setFirstResult(sp.getFirst()); }/*w w w . ja va2 s.co m*/ if (sp.getPageSize() > 0) { query.setMaxResults(sp.getPageSize()); } else if (sp.getMaxResults() > 0) { query.setMaxResults(sp.getMaxResults()); } }
From source file:org.apache.oozie.tools.OozieDBExportCLI.java
private static int exportTableToJSON(Query query, ZipOutputStream zipOutputStream, String filename) throws IOException { Gson gson = new Gson(); ZipEntry zipEntry = new ZipEntry(filename); zipOutputStream.putNextEntry(zipEntry); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(zipOutputStream, "UTF-8")); query.setMaxResults(LIMIT);// w ww.j a va 2 s .co m int exported = 0; List<?> list = query.getResultList(); while (!list.isEmpty()) { query.setFirstResult(exported); list = query.getResultList(); for (Object w : list) { exported++; gson.toJson(w, writer); writer.newLine(); } } writer.flush(); zipOutputStream.closeEntry(); return exported; }
From source file:org.rhq.core.domain.server.PersistenceUtility.java
public static void setDataPage(Query query, PageControl pageControl) { if (pageControl.getPageSize() > 0) { query.setFirstResult(pageControl.getStartRow()); query.setMaxResults(pageControl.getPageSize()); }/*from www .j a va2 s . c om*/ }
From source file:org.rhq.core.domain.server.PersistenceUtility.java
/** * Creates and executes a filter query for a collection relationship. This executes without passing back the query * object because the most common case is to simply paginate for a relationship. Use the createFilter method to * create more generic filters and get access to the hibernate query object for setting parameters etc. * * @param entityManager/*from ww w . ja v a 2s . co m*/ * @param collection * @param pageControl * * @return the result list of the entities from the filtered relationship */ @SuppressWarnings("unchecked") public static PageList createPaginationFilter(EntityManager entityManager, Collection collection, PageControl pageControl) { if (collection == null) { return new PageList(pageControl); } String filter = ""; if (pageControl.getPrimarySortColumn() != null) { PageOrdering order = (pageControl.getPrimarySortOrder() == null) ? PageOrdering.ASC : pageControl.getPrimarySortOrder(); filter = getOrderByFragment(new OrderingField(pageControl.getPrimarySortColumn(), order)); } org.hibernate.Query query = getHibernateSession(entityManager).createFilter(collection, filter); if (pageControl.getPageSize() > 0) { query.setFirstResult(pageControl.getPageNumber() * pageControl.getPageSize()); query.setMaxResults(pageControl.getPageSize()); } // TODO GH: Always flushing is probably not what we really want here // relationship filters don't seem to cause the proper flush, so manually flush getHibernateSession(entityManager).flush(); // TODO GH: This can only create unbounded PageLists since I don't know how to do a count query to find the size return new PageList<Object>(query.list(), pageControl); }
From source file:org.ow2.sirocco.cloudmanager.core.utils.QueryHelper.java
public static <E> QueryResult<E> getCollectionItemList(final EntityManager em, final QueryParamsBuilder params) throws InvalidRequestException { StringBuffer whereClauseSB = new StringBuffer(); if (params.getTenantId() != null) { whereClauseSB.append(" v.tenant.id=:tenantId "); }/*from w w w . j a v a 2 s. co m*/ if (params.getStateToIgnore() != null) { if (whereClauseSB.length() > 0) { whereClauseSB.append(" AND "); } whereClauseSB.append(" vv.state<>" + params.getStateToIgnore().getClass().getName() + "." + params.getStateToIgnore().name() + " "); } if (whereClauseSB.length() > 0) { whereClauseSB.append(" AND "); } whereClauseSB.append("v.uuid=:cid "); if (params.getFilters() != null) { String filterClause; try { filterClause = QueryHelper.generateFilterClause(params.getFilters(), "vv", params.getClazz().getName() + "$State."); } catch (ParseException ex) { throw new InvalidRequestException("Parsing error in filter expression " + ex.getMessage()); } catch (TokenMgrError ex) { throw new InvalidRequestException(ex.getMessage()); } if (!filterClause.isEmpty()) { if (whereClauseSB.length() > 0) { whereClauseSB.append(" AND "); } whereClauseSB.append(filterClause); } } String whereClause = whereClauseSB.toString(); String queryExpression = "SELECT COUNT(vv) FROM " + params.getEntityType() + " vv, " + params.getContainerType() + " v WHERE vv MEMBER OF v." + params.getContainerAttributeName() + " AND " + whereClause; try { int count = ((Number) em.createQuery(queryExpression).setParameter("cid", params.getContainerId()) .setParameter("tenantId", params.getTenantId()).getSingleResult()).intValue(); queryExpression = "SELECT vv FROM " + params.getEntityType() + " vv, " + params.getContainerType() + " v WHERE vv MEMBER OF v." + params.getContainerAttributeName() + " AND " + whereClause + " ORDER BY vv.id"; Query query = em.createQuery(queryExpression).setParameter("cid", params.getContainerId()) .setParameter("tenantId", params.getTenantId()); if (params.getFirst() != null) { query.setFirstResult(params.getFirst()); } if (params.getLast() != null) { if (params.getFirst() != null) { query.setMaxResults(params.getLast() - params.getFirst() + 1); } else { query.setMaxResults(params.getLast() + 1); } } List<E> queryResult = query.getResultList(); if (params.getAttributes() != null && params.getAttributes().size() != 0) { List<E> items = new ArrayList<E>(); for (E from : queryResult) { E resource = (E) params.getClazz().newInstance(); for (int i = 0; i < params.getAttributes().size(); i++) { try { PropertyUtils.setSimpleProperty(resource, params.getAttributes().get(i), PropertyUtils.getSimpleProperty(from, params.getAttributes().get(i))); } catch (NoSuchMethodException e) { // ignore wrong attribute name } } items.add(resource); } return new QueryResult<E>(count, items); } else { return new QueryResult<E>(count, queryResult); } } catch (IllegalArgumentException ex) { ex.printStackTrace(); throw new InvalidRequestException(ex.getMessage()); } catch (InstantiationException ex) { ex.printStackTrace(); throw new InvalidRequestException(ex.getMessage()); } catch (IllegalAccessException ex) { ex.printStackTrace(); throw new InvalidRequestException(ex.getMessage()); } catch (InvocationTargetException ex) { throw new InvalidRequestException(ex.getMessage()); } }
From source file:models.SkillTag.java
public static Page<SkillTagListVo> listTagByCate(Long cateId, Integer page, Integer start, Integer limit, String searchText) {//from w ww .j av a 2 s . c o m String hql1 = "select count(s) from SkillTag s where s.industryId=? and s.id<>?"; if (searchText != null && !"".equals(searchText)) { hql1 += " and (s.tagName like ? or s.tagNameEn like ?)"; } Query query1 = JPA.em().createQuery(hql1); query1.setParameter(1, cateId); query1.setParameter(2, cateId); if (searchText != null && !"".equals(searchText)) { query1.setParameter(3, "%" + searchText + "%"); query1.setParameter(4, "%" + searchText + "%"); } Long total = (Long) query1.getSingleResult(); String hql2 = "from SkillTag s left join fetch s.industry where s.industryId=? and s.id<>?"; if (searchText != null && !"".equals(searchText)) { hql2 += " and (s.tagName like ? or s.tagNameEn like ?)"; } hql2 += " order by s.seq asc"; Query query2 = JPA.em().createQuery(hql2); query2.setParameter(1, cateId); query2.setParameter(2, cateId); if (searchText != null && !"".equals(searchText)) { query2.setParameter(3, "%" + searchText + "%"); query2.setParameter(4, "%" + searchText + "%"); } List<SkillTag> skillTags = query2.setFirstResult(start).setMaxResults(limit).getResultList(); Page<SkillTagListVo> p = new Page<SkillTagListVo>(); p.setTotal(total); List<SkillTagListVo> sklvs = new ArrayList<SkillTagListVo>(); for (SkillTag skillTag : skillTags) { SkillTagListVo sklv = new SkillTagListVo(); sklv.setId(skillTag.id); if (skillTag.industry != null) { sklv.setIndustryId(skillTag.industry.id); sklv.setIndustryName(skillTag.industry.tagName); } sklv.setHits(skillTag.hits); sklv.setTagNameEn(skillTag.tagNameEn); sklv.setTagName(skillTag.tagName); sklv.setSeq(skillTag.seq); sklv.setTagType(skillTag.tagType); sklvs.add(sklv); } p.setData(sklvs); return p; }
From source file:com.impetus.kundera.rest.common.EntityUtils.java
/** * @param queryString/*ww w. j a v a 2 s . c o m*/ * @param q */ public static void setQueryParameters(String queryString, String parameterString, Query q) { Map<String, String> paramsMap = new HashMap<String, String>(); StringTokenizer st = new StringTokenizer(parameterString, "&"); while (st.hasMoreTokens()) { String element = st.nextToken(); paramsMap.put(element.substring(0, element.indexOf("=")), element.substring(element.indexOf("=") + 1, element.length())); } KunderaQuery kq = ((QueryImpl) q).getKunderaQuery(); Set<Parameter<?>> parameters = kq.getParameters(); for (String paramName : paramsMap.keySet()) { String value = paramsMap.get(paramName); if (paramName.equalsIgnoreCase("firstResult")) { q.setFirstResult(Integer.parseInt(value)); } else if (paramName.equalsIgnoreCase("maxResult")) { q.setMaxResults(Integer.parseInt(value)); } else if (StringUtils.isNumeric(paramName)) { for (Parameter param : parameters) { if (param.getPosition() == Integer.parseInt(paramName)) { Class<?> paramClass = param.getParameterType(); PropertyAccessor accessor = PropertyAccessorFactory.getPropertyAccessor(paramClass); Object paramValue = accessor.fromString(paramClass, value); q.setParameter(Integer.parseInt(paramName), paramValue); break; } } } else { for (Parameter param : parameters) { if (param.getName().equals(paramName)) { Class<?> paramClass = param.getParameterType(); PropertyAccessor accessor = PropertyAccessorFactory.getPropertyAccessor(paramClass); Object paramValue = accessor.fromString(paramClass, value); q.setParameter(paramName, paramValue); break; } } } } }
From source file:org.ow2.sirocco.cloudmanager.core.utils.QueryHelper.java
public static <E extends Identifiable> QueryResult<E> getEntityList(final EntityManager em, final QueryParamsBuilder params) throws InvalidRequestException { StringBuffer whereClauseSB = new StringBuffer(); if (params.getTenantId() != null) { if (!params.isReturnPublicEntities()) { whereClauseSB.append(" v.tenant.id=:tenantId "); } else {/*from w w w . j a va2 s. c om*/ whereClauseSB.append( "( v.tenant.id=:tenantId OR v.visibility = org.ow2.sirocco.cloudmanager.model.cimi.extension.Visibility.PUBLIC) "); } } if (params.getStateToIgnore() != null) { if (whereClauseSB.length() > 0) { whereClauseSB.append(" AND "); } whereClauseSB.append(" v.state<>" + params.getStateToIgnore().getClass().getName() + "." + params.getStateToIgnore().name() + " "); } if (params.isFilterEmbbededTemplate()) { if (whereClauseSB.length() > 0) { whereClauseSB.append(" AND "); } whereClauseSB.append(" v.isEmbeddedInSystemTemplate=false "); } if (params.getFilters() != null) { String filterClause; try { filterClause = QueryHelper.generateFilterClause(params.getFilters(), "v", params.getClazz().getName() + "$State."); } catch (ParseException ex) { throw new InvalidRequestException("Parsing error in filter expression " + ex.getMessage()); } catch (TokenMgrError ex) { throw new InvalidRequestException(ex.getMessage()); } if (!filterClause.isEmpty()) { if (whereClauseSB.length() > 0) { whereClauseSB.append(" AND "); } whereClauseSB.append(filterClause); } } if (params.getMarker() != null) { try { Resource resourceAtMarker = (Resource) em .createQuery("SELECT r FROM " + params.getEntityType() + " r WHERE uuid=:uuid") .setParameter("uuid", params.getMarker()).getSingleResult(); if (whereClauseSB.length() > 0) { whereClauseSB.append(" AND "); } whereClauseSB.append(" v.id>" + resourceAtMarker.getId() + " "); } catch (NoResultException e) { throw new InvalidRequestException("Invalid marker " + params.getMarker()); } } String whereClause = whereClauseSB.toString(); try { int count = ((Number) em .createQuery("SELECT COUNT(v) FROM " + params.getEntityType() + " v WHERE " + whereClause) .setParameter("tenantId", params.getTenantId()).getSingleResult()).intValue(); Query query = em.createQuery( "SELECT v FROM " + params.getEntityType() + " v WHERE " + whereClause + " ORDER BY v.id DESC") .setParameter("tenantId", params.getTenantId()); if (params.getLimit() != null) { query.setMaxResults(params.getLimit()); } else { if (params.getFirst() != null) { query.setFirstResult(params.getFirst()); } if (params.getLast() != null) { if (params.getFirst() != null) { query.setMaxResults(params.getLast() - params.getFirst() + 1); } else { query.setMaxResults(params.getLast() + 1); } } } List<E> queryResult = query.getResultList(); if (params.getAttributes() != null && params.getAttributes().size() != 0) { List<E> items = new ArrayList<E>(); for (E from : queryResult) { E resource = (E) params.getClazz().newInstance(); for (int i = 0; i < params.getAttributes().size(); i++) { try { PropertyUtils.setSimpleProperty(resource, params.getAttributes().get(i), PropertyUtils.getSimpleProperty(from, params.getAttributes().get(i))); } catch (NoSuchMethodException e) { // ignore wrong attribute name } } resource.setUuid(from.getUuid()); if (resource instanceof ICloudProviderResource) { ICloudProviderResource fromResource = (ICloudProviderResource) from; ICloudProviderResource toResource = (ICloudProviderResource) resource; toResource.setLocation(fromResource.getLocation()); toResource.setProviderAssignedId(fromResource.getProviderAssignedId()); toResource.setCloudProviderAccount(fromResource.getCloudProviderAccount()); } else if (resource instanceof IMultiCloudResource) { IMultiCloudResource fromResource = (IMultiCloudResource) from; IMultiCloudResource toResource = (IMultiCloudResource) resource; toResource.setProviderMappings(fromResource.getProviderMappings()); } items.add(resource); } return new QueryResult<E>(count, items); } else { return new QueryResult<E>(count, queryResult); } } catch (IllegalArgumentException ex) { ex.printStackTrace(); throw new InvalidRequestException(ex.getMessage()); } catch (InstantiationException ex) { ex.printStackTrace(); throw new InvalidRequestException(ex.getMessage()); } catch (IllegalAccessException ex) { ex.printStackTrace(); throw new InvalidRequestException(ex.getMessage()); } catch (InvocationTargetException ex) { throw new InvalidRequestException(ex.getMessage()); } }