/** * prepare query based on criteria * * @param session hib session * @return the query */ private Criteria attachCriteriaInfo(Session session) { Criteria query = null; if (StringUtils.isBlank(this.entityName)) { if (StringUtils.isBlank(this.alias)) { query = session.createCriteria(this.persistentClass); } else { query = session.createCriteria(this.persistentClass, alias); } } else { query = session.createCriteria(this.entityName); } // add criterions if (this.criterions != null) { query.add(this.criterions); } boolean secondLevelCaching = HibUtils.secondLevelCaching( ByCriteriaStatic.this.cacheable, ByCriteriaStatic.this.queryOptions); query.setCacheable(secondLevelCaching); if (secondLevelCaching) { String secondLevelCacheRegion = HibUtils.secondLevelCacheRegion( ByCriteriaStatic.this.cacheRegion, ByCriteriaStatic.this.queryOptions); if (!StringUtils.isBlank(secondLevelCacheRegion)) { query.setCacheRegion(secondLevelCacheRegion); } } QuerySort querySort = this.queryOptions == null ? null : this.queryOptions.getQuerySort(); if (querySort != null) { List<QuerySortField> sorts = querySort.getQuerySortFields(); for (QuerySortField theSort : GrouperUtil.nonNull(sorts)) { Order order = theSort.isAscending() ? Order.asc(theSort.getColumn()) : Order.desc(theSort.getColumn()); query.addOrder(order); } } QueryPaging queryPaging = this.queryOptions == null ? null : this.queryOptions.getQueryPaging(); if (queryPaging != null) { // GRP-1024: sql server problems with paging page number when not initted if (queryPaging.getFirstIndexOnPage() < 0) { query.setFirstResult(0); } else { query.setFirstResult(queryPaging.getFirstIndexOnPage()); } query.setMaxResults(queryPaging.getPageSize()); } return query; }
@SuppressWarnings("unchecked") public List<T> findByExample( T instance, Set<String> excludedProperties, Set<String> includedCollections, int fromRecord, int toRecord) { try { Example exampleInstance = create(instance); // Exclude the properties if (excludedProperties != null) { for (String excludedProperty : excludedProperties) { exampleInstance = exampleInstance.excludeProperty(excludedProperty); } } Criteria myCriteria = sessionFactory.getCurrentSession().createCriteria(clazz.getCanonicalName()); if (includedCollections != null) { // Include the collections for (String includedCollection : includedCollections) { myCriteria.setFetchMode(includedCollection, FetchMode.JOIN); } } // set the LIMIT if (fromRecord >= 0 && toRecord >= 0) { if (fromRecord < toRecord) { myCriteria.setFirstResult(fromRecord); myCriteria.setMaxResults(toRecord - fromRecord); } else { myCriteria.setFirstResult(toRecord); myCriteria.setMaxResults(fromRecord - toRecord); } } // Only get distinct Root entities myCriteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY); // get the results List<T> results = (List<T>) myCriteria.add(exampleInstance).list(); return results; } catch (RuntimeException re) { throw re; } }
@GET @SuppressWarnings("unchecked") public ResultList<InfoClinica> list( @QueryParam("count") Integer count, @QueryParam("page") Integer page, @QueryParam("search.valor") String valor) { Session session = (Session) em.getDelegate(); Criteria criteria = session.createCriteria(getType()); Criteria countCriteria = session.createCriteria(getType()); criteria.addOrder(Order.asc("valor")); if (count != null) { criteria.setMaxResults(count); } if (count != null && page != null) { criteria.setFirstResult((page - 1) * count); } if (valor != null) { criteria.add(Restrictions.ilike("nome", valor, ANYWHERE)); countCriteria.add(Restrictions.ilike("nome", valor, ANYWHERE)); } List<InfoClinica> list = criteria.list(); Long totalResults = (Long) countCriteria.setProjection(Projections.rowCount()).uniqueResult(); return new ResultList<>(list, page, count, totalResults.intValue()); }
/* * 通过分页查询呢 * * * 方法 八 * * * */ public ArrayList listprojectbypage(int page, int count) { ArrayList<Project> projectList = new ArrayList<Project>(); HibernateSessionFactory hibernateSessionFactory = new HibernateSessionFactory(); Session session = HibernateSessionFactory.getsSession(); // System.out.println(session); try { Transaction ts = session.beginTransaction(); Query query = session.createQuery("from Project where pro_id=?"); Criteria criteria = session.createCriteria(Project.class); criteria.setFirstResult((page - 1) * count); criteria.setMaxResults(count); projectList = (ArrayList) criteria.list(); ts.commit(); System.out.println("dao中的通过分页查询项目的方法:" + projectList); System.out.println("*****" + projectList.size()); HibernateSessionFactory.closeSession(); } catch (HibernateException e) { e.printStackTrace(); } // session.update(pro); // System.out.println(projectList); return projectList; }
/** * 使用指定查询对象进行分页查询. * * @param criteria 实体的查询对象 * @param pageNo 页号,从1开始. * @param pageSize 每页中的记录数 * @return 当前页的分页对象 */ public Page pagedQuery(Criteria criteria, int pageNo, int pageSize) { CriteriaImpl impl = (CriteriaImpl) criteria; // 先把Projection和OrderBy条件取出来,清空两者来执行Count操作 Projection projection = impl.getProjection(); List<CriteriaImpl.OrderEntry> orderEntries; try { orderEntries = (List) BeanUtils.getPrivateProperty(impl, "orderEntries"); BeanUtils.setPrivateProperty(impl, "orderEntries", new ArrayList()); } catch (Exception e) { logger.error(e.getMessage()); throw new InternalError(" Runtime Exception impossibility throw "); } // 执行查询 long totalCount = ((Number) criteria.setProjection(Projections.rowCount()).uniqueResult()).longValue(); // 将之前的Projection和OrderBy条件重新设回去 criteria.setProjection(projection); if (projection == null) { criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY); } try { BeanUtils.setPrivateProperty(impl, "orderEntries", orderEntries); } catch (Exception e) { logger.error(e.getMessage()); throw new InternalError(" Runtime Exception impossibility throw "); } // 返回分页对象 if (totalCount < 1) return new Page(); int startIndex = Page.getStartOfPage(pageNo, pageSize); List list = criteria.setFirstResult(startIndex).setMaxResults(pageSize).list(); return new Page(startIndex, totalCount, pageSize, list); }
@SuppressWarnings("unchecked") public List<T> findByCriteria( final int firstResult, final int maxResults, final ProjectionList projections, final Criterion... criterion) { Session session = (Session) getEntityManager().getDelegate(); Criteria crit = session.createCriteria(getEntityClass()); crit.setProjection(projections); crit.setResultTransformer(Transformers.aliasToBean(getEntityClass())); for (final Criterion c : criterion) { crit.add(c); } if (firstResult > 0) { crit.setFirstResult(firstResult); } if (maxResults > 0) { crit.setMaxResults(maxResults); } final List<T> result = crit.list(); return result; }
@Override public List<Retirement> queryList( Retirement r, int s, int size, String ks, String js, String eq, String type) { Criteria c = buildCondition(r, ks, js, eq, type); c.setFirstResult(s).setMaxResults(size); return queryByPage(c); }
@SuppressWarnings("unchecked") @Override public List<PersonneStatut> rechercherStatutParCriteres(DimensionCriteresRechercheDto criteres) { final Criteria criteria = createCriteria(PersonneStatut.class); // Critère sur l'identifiant if (criteres.getId() != null) { criteria.add(Restrictions.eq("id", criteres.getId())); } // Critère sur le libelle if (criteres.getLibelle() != null && !criteres.getLibelle().equals("")) { criteria.add(Restrictions.ilike("libelle", criteres.getLibelle().toLowerCase() + "%")); } // Critère sur la visibilité if (criteres.getVisible() != null) { criteria.add(Restrictions.eq("visible", criteres.getVisible())); } // Maxresults if (criteres.getMaxResults() != null) { criteria.setFirstResult(0); criteria.setMaxResults(criteres.getMaxResults()); } // Ordonner les éléments criteria.addOrder(Order.asc("ordre")); criteria.addOrder(Order.asc("libelle")); return criteria.list(); }
public List<T> findAll(Integer number, Integer offset, String orderByPropertyName, boolean asc) { Session session = openSession(true); List<T> results = Lists.newArrayList(); try { Criteria criteria = criteria().setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); if (number != 1) { criteria.setFirstResult(number - 1); } if (offset != 0) { criteria.setMaxResults(offset); } if (asc) { criteria.addOrder(Order.asc(orderByPropertyName)); } else { criteria.addOrder(Order.desc(orderByPropertyName)); } results = list(criteria); for (T result : results) { result.init(); } commitTransaction(session, true); } catch (Exception e) { rollbackTransaction(session, true); } finally { closeSession(session); } return results; }
@SuppressWarnings("unchecked") public List<T> find(Class<T> clazz, String title, int firstRow, int maxRow, String server) { /** &&短路符号 title.length()不会抛出异常(可省掉的) */ if (title != null && title.length() > 0) { /** 防止title=" "出现 */ title = title.replace(" ", ""); if (title.length() == 0) return null; } else { return null; } Criteria criteria = this.getSession().createCriteria(clazz); criteria.add( or( Restrictions.like("title", "%" + title + "%"), Restrictions.like("note", "%" + title + "%"))); criteria.addOrder(Order.asc("title")); if (null != server) { criteria.add(eq("server", server)); } /** 分页? 需要做一些优化 */ criteria.setFirstResult(firstRow); criteria.setMaxResults(maxRow); List<T> list = criteria.list(); return ((list == null) || list.isEmpty()) ? null : list; }
/** * 使用检索标准对象分页查询 * * @param detachedCriteria * @param page * @return */ @SuppressWarnings("unchecked") public Page<T> find(Page<T> page, DetachedCriteria detachedCriteria) { // get count if (!page.isDisabled() && !page.isNotCount()) { page.setCount(count(detachedCriteria)); if (page.getCount() < 1) { return page; } } Criteria criteria = detachedCriteria.getExecutableCriteria(getSession()); criteria.setResultTransformer(Criteria.ROOT_ENTITY); // set page if (!page.isDisabled()) { criteria.setFirstResult(page.getFirstResult()); criteria.setMaxResults(page.getMaxResults()); } // order by if (StringUtils.isNotBlank(page.getOrderBy())) { for (String order : StringUtils.split(page.getOrderBy(), ",")) { String[] o = StringUtils.split(order, " "); if (o.length >= 1) { criteria.addOrder(Order.asc(o[0])); } else if (o.length >= 2) { if ("DESC".equals(o[1].toUpperCase())) { criteria.addOrder(Order.desc(o[0])); } else { criteria.addOrder(Order.asc(o[0])); } } } } page.setList(criteria.list()); return page; }
@Override public Iterable<T> findUsingQueryModel(QueryModel queryModel) { if (accessControlContextProvider == null || roleAllowsAccess(queryModel.getAccessControlContext().getRole())) { Criteria criteria = buildCriteria(queryModel); if (queryModel.getSorts() != null) { for (Sort sort : queryModel.getSorts()) { criteria.addOrder( sort.getSortDirection() == SortDirection.Ascending ? Order.asc(sort.getField()) : Order.desc(sort.getField())); } } if (queryModel.getMaxResults() > 0) { criteria.setMaxResults(queryModel.getMaxResults()); } if (queryModel.getFirstResult() > 0) { criteria.setFirstResult(queryModel.getFirstResult()); } //noinspection unchecked return criteria.list(); } else { //noinspection unchecked return createEntryBasedQuery(queryModel).list(); } }
public List<T> findAll(int start, int max) { Criteria criteria = getSession().createCriteria(t.getClass()); criteria.setFirstResult(start); criteria.setMaxResults(max); List result = criteria.list(); return result; }
@SuppressWarnings("unchecked") public List<Token> findTokens( Token search, int first, int pageSize, String sortField, SortOrder sortOrder) throws DAOException { List<Token> results = null; Session session = null; try { session = getSession(); Criteria criteria = criteria(session, search); criteria.setFirstResult(first); criteria.setMaxResults(pageSize); if (sortField == null) { sortField = "tokenId"; } Order ord = (sortOrder == null || sortOrder.equals(SortOrder.UNSORTED) || sortOrder.equals(SortOrder.ASCENDING)) ? Order.asc(sortField) : Order.desc(sortField); criteria.addOrder(ord); results = criteria.list(); } catch (Exception e) { throw new DAOException(e); } finally { if (session != null) { session.close(); } } return results; }
public Map<String, Object> lista(Map<String, Object> params) { log.debug("Buscando lista de facturas con params {}", params); if (params == null) { params = new HashMap<>(); } if (!params.containsKey("max")) { params.put("max", 10); } else { params.put("max", Math.min((Integer) params.get("max"), 100)); } if (params.containsKey("pagina")) { Long pagina = (Long) params.get("pagina"); Long offset = (pagina - 1) * (Integer) params.get("max"); params.put("offset", offset.intValue()); } if (!params.containsKey("offset")) { params.put("offset", 0); } Criteria criteria = currentSession().createCriteria(FacturaAlmacen.class); Criteria countCriteria = currentSession().createCriteria(FacturaAlmacen.class); if (params.containsKey("almacen")) { criteria.createCriteria("almacen").add(Restrictions.idEq(params.get("almacen"))); countCriteria.createCriteria("almacen").add(Restrictions.idEq(params.get("almacen"))); } if (params.containsKey("filtro")) { String filtro = (String) params.get("filtro"); Disjunction propiedades = Restrictions.disjunction(); propiedades.add(Restrictions.ilike("folio", filtro, MatchMode.ANYWHERE)); criteria.add(propiedades); countCriteria.add(propiedades); } if (params.containsKey("order")) { String campo = (String) params.get("order"); if (params.get("sort").equals("desc")) { criteria.addOrder(Order.desc(campo)); } else { criteria.addOrder(Order.asc(campo)); } } else { criteria.createCriteria("estatus").addOrder(Order.asc("prioridad")); } criteria.addOrder(Order.desc("fechaModificacion")); if (!params.containsKey("reporte")) { criteria.setFirstResult((Integer) params.get("offset")); criteria.setMaxResults((Integer) params.get("max")); } params.put("facturas", criteria.list()); countCriteria.setProjection(Projections.rowCount()); params.put("cantidad", (Long) countCriteria.list().get(0)); return params; }
public Pager list(String username, int pageSize, int pageNo) { Session session = null; Pager pager = null; try { session = HibernateSessionFactory.currentSession(); Criteria criteria = session.createCriteria(Schedule.class); criteria.add(Restrictions.eq("username", username)); int rowCount = ((Long) criteria.setProjection(Projections.rowCount()).uniqueResult()).intValue(); criteria.setProjection(null); int startIndex = pageSize * (pageNo - 1); criteria.addOrder(Order.desc("year")); criteria.addOrder(Order.desc("month")); criteria.addOrder(Order.desc("day")); criteria.setFirstResult(startIndex); criteria.setMaxResults(pageSize); List<?> result = criteria.list(); pager = new Pager(pageSize, pageNo, rowCount, result); } catch (HibernateException e) { pager = new Pager(pageSize, pageNo, 0, new ArrayList<Object>()); throw e; } finally { HibernateSessionFactory.closeSession(); } return pager; }
/** * 分页查询函数,使用已设好查询条件与排序的<code>Criteria</code>. * * @param pageNo 页号,从1开始. * @return 含总记录数和当前页数据的Page对象. */ @SuppressWarnings("unchecked") public Page<T> pagedQuery(Criteria criteria, int pageNo, int pageSize) { Assert.notNull(criteria); Assert.isTrue(pageNo >= 1, "pageNo should start from 1"); CriteriaImpl impl = (CriteriaImpl) criteria; // 先把Projection和OrderBy条件取出来,清空两者来执行Count操作 Projection projection = impl.getProjection(); List<CriteriaImpl.OrderEntry> orderEntries; try { orderEntries = (List) BeanUtils.forceGetProperty(impl, "orderEntries"); BeanUtils.forceSetProperty(impl, "orderEntries", new ArrayList()); } catch (Exception e) { throw new InternalError(" Runtime Exception impossibility throw "); } // 执行查询 long totalCount = (Long) criteria.setProjection(Projections.rowCount()).uniqueResult(); // 将之前的Projection和OrderBy条件重新设回去 criteria.setProjection(projection); if (projection == null) { criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY); } try { BeanUtils.forceSetProperty(impl, "orderEntries", orderEntries); } catch (Exception e) { throw new InternalError(" Runtime Exception impossibility throw "); } // 返回分页对象 if (totalCount < 1) return new Page<T>(); int startIndex = Page.getStartOfPage(pageNo, pageSize); ; List<T> list = criteria.setFirstResult(startIndex).setMaxResults(pageSize).list(); return new Page(startIndex, totalCount, pageSize, list); }
@Override @SuppressWarnings("unchecked") public List<ProgramInstance> getByStatus( ProgramStatus status, Program program, Collection<Integer> orgunitIds, Date startDate, Date endDate, Integer min, Integer max) { Criteria criteria = getCriteria( Restrictions.eq("program", program), Restrictions.between("enrollmentDate", startDate, endDate)) .createAlias("entityInstance", "entityInstance") .createAlias("entityInstance.organisationUnit", "organisationUnit") .add(Restrictions.in("organisationUnit.id", orgunitIds)) .add(Restrictions.eq("status", status)); if (min != null) { criteria.setFirstResult(min); } if (max != null) { criteria.setMaxResults(max); } return criteria.list(); }
@Override public <T extends GettableById> List<T> get( Class<T> bookEntityClass, int from, int to, Map<String, List<Criterion>> restrictions, OrderByFilter filter) { validateTransaction(); Criteria criteria = getSession().createCriteria(bookEntityClass); criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); criteria.setFirstResult(from); if (to != 0) criteria.setMaxResults(to); for (String key : restrictions.keySet()) { if (key.equals(RestrictionsFields.MAIN_RESTRICTIONS)) { for (Criterion restriction : restrictions.get(RestrictionsFields.MAIN_RESTRICTIONS)) criteria.add(restriction); } else if (restrictions.get(key).size() > 0) { Criteria c = criteria.createCriteria(key); for (Criterion restriction : restrictions.get(key)) c.add(restriction); } } if (filter != null) { if (filter.getDirection().equals(OrderByFilter.ASC)) criteria.addOrder(Order.asc(filter.field)); else criteria.addOrder(Order.desc(filter.field)); } return criteria.list(); }
@SuppressWarnings("unchecked") public List<T> findAllFromTo(Integer first, Integer last) { Criteria criteria = getSession().createCriteria(persistentClass); criteria.setFirstResult(first); criteria.setMaxResults(last - first); return criteria.list(); }
public List<UserCountDTO> getCurrentUserCountList( String sortField, int order, int start, int gridTableSize, String searchq) throws Exception { int count = start; List<UserCountDTO> dtoList = null; List<UserCountDTO> dtoListCount = new ArrayList<UserCountDTO>(); Session session = getSession(); session.getTransaction().begin(); Criteria criteria = session .createCriteria(SessionDetails.class, "sessionDetails") .add(Restrictions.eq("status", "ACTIVE")); criteria.addOrder(Order.asc("SID")); criteria.setFirstResult(start).setMaxResults(gridTableSize); criteria.setProjection(Projections.projectionList().add(Projections.property("SID").as("sid"))); dtoList = criteria.setResultTransformer(Transformers.aliasToBean(UserCountDTO.class)).list(); session.getTransaction().commit(); session.close(); if (dtoList.size() > 0) { for (UserCountDTO dto : dtoList) { dto.setCountId(count + 1); dtoListCount.add(dto); count += 1; } } return dtoListCount; }
public Collection<Role> find( final Enterprise enterprise, final String filter, final String orderBy, final boolean desc, final Integer offset, final Integer numResults, final boolean discardNullEnterprises) { Criteria criteria = createCriteria(enterprise, filter, orderBy, desc, discardNullEnterprises); Long total = count(criteria); criteria = createCriteria(enterprise, filter, orderBy, desc, discardNullEnterprises); criteria.setFirstResult(offset * numResults); criteria.setMaxResults(numResults); List<Role> result = getResultList(criteria); PagedList<Role> page = new PagedList<Role>(); page.addAll(result); page.setCurrentElement(offset); page.setPageSize(numResults); page.setTotalResults(total.intValue()); return page; }
public List getAutoMobileList( int startLimit, int endLimit, AutomobileExpense autoMobile, String search_1st_order_by) { Session session = sessionFactory.openSession(); List list = new ArrayList(); try { Criteria criteria = createAutoMobileCriteria(session, autoMobile, ""); if (StringUtils.isNotBlank(search_1st_order_by)) { criteria.addOrder(Order.desc(search_1st_order_by)); } if (StringUtils.isBlank(search_1st_order_by)) { criteria.addOrder(Order.desc("automobileExpenseId")); } criteria.setFirstResult(startLimit); criteria.setMaxResults(endLimit); list = criteria.list(); } catch (HibernateException e) { e.printStackTrace(); } finally { session.close(); } return list; }
@SuppressWarnings("unchecked") public List<Payment> listPayments(int min, int max) { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Payment.class); criteria.setFirstResult(min).setMaxResults(max); criteria.addOrder(Order.desc("paymentDate")); return criteria.list(); }
public List<T> findByKey(String key, Object object, int start, int max) { Criteria criteria = getSession().createCriteria(t.getClass()); criteria.add(Restrictions.ilike(key, object)); criteria.setFirstResult(start); criteria.setMaxResults(max); List result = criteria.list(); return result; }
@Override @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) public List<ConsoleInfo> getConsoleInfos(int start, int pageSize) { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(ConsoleInfo.class); criteria.setFirstResult(start).setMaxResults(pageSize); return criteria.list(); }
public List<Servicio> obtenerServiciosPorRed(Long idRed, Integer start, Integer limit) { Criteria c = this.obtenerCriteriaServiciosPorRed(idRed); if (start != null && limit != null) { c.setFirstResult(start); c.setMaxResults(limit); } return c.list(); }
@SuppressWarnings("unchecked") public List<IncomeReceipt> getListIncomeReceipt(boolean includeVoided, int start, int end) { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(IncomeReceipt.class); if (!includeVoided) criteria.add(Restrictions.eq("voided", false)); criteria.setFirstResult(start).setMaxResults(end); return criteria.list(); }
@Override @SuppressWarnings("unchecked") public List<User> getAllOrderedName(int first, int max) { Criteria criteria = getCriteria(); criteria.addOrder(Order.asc("surname")).addOrder(Order.asc("firstName")); criteria.setFirstResult(first); criteria.setMaxResults(max); return criteria.list(); }
@Override @SuppressWarnings("unchecked") public Collection<OrganisationUnit> getBetweenByStatus(boolean status, int first, int max) { Criteria criteria = getCriteria().add(Restrictions.eq("active", status)); criteria.setFirstResult(first); criteria.setMaxResults(max); return criteria.list(); }