/** 총 낙서 갯수를 반환한다. */ public int getTotalRowCount() throws DataAccessException { return (Integer) getCurrentSession() .createCriteria(Graffiti.class) .setProjection(Projections.rowCount()) .uniqueResult(); }
/** * 使用检索标准对象查询记录数 * * @param detachedCriteria * @return */ @SuppressWarnings("rawtypes") public long count(DetachedCriteria detachedCriteria) { Criteria criteria = detachedCriteria.getExecutableCriteria(getSession()); long totalCount = 0; try { // Get orders Field field = CriteriaImpl.class.getDeclaredField("orderEntries"); field.setAccessible(true); List orderEntrys = (List) field.get(criteria); // Remove orders field.set(criteria, new ArrayList()); // Get count criteria.setProjection(Projections.rowCount()); totalCount = Long.valueOf(criteria.uniqueResult().toString()); // Clean count criteria.setProjection(null); // Restore orders field.set(criteria, orderEntrys); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return totalCount; }
public long countTotalDevice() { return (long) getCurrentSession() .createCriteria(DeviceInfo.class) .setProjection(Projections.rowCount()) .uniqueResult(); }
/** * 查询一个对象的属性值在数据库中是不是唯一 * * @param entity 实体对象 * @param propertyNames 属性的名称,可多个 如:"prop1,prop2" * @return 针对 编辑 对象保存时 如果和其它 对象 属性名称相同 抛出异常问题 重写此方法 */ public boolean isUnique(Object entity, String propertyNames) { Class<?> clazz = getTrueClass(entity); Criteria criteria = createCriteria(clazz).setProjection(Projections.rowCount()); String[] nameList = propertyNames.split(","); try { boolean isQuery = false; for (String name : nameList) { Object obj = PropertyUtils.getProperty(entity, name); if (obj != null) { criteria.add(Restrictions.eq(name, obj)); isQuery = true; } else { isQuery = false; } } if (!isQuery) { return true; } String idName = getIdName(clazz); Serializable id = getId(clazz, entity); if (id != null) { criteria.add(Restrictions.not(Restrictions.eq(idName, id))); } } catch (Exception e) { ReflectionUtils.handleReflectionException(e); } this.getSession().evict(entity); return (Integer) criteria.uniqueResult() == 0; }
@Override public long standbyCount() throws OperationalException { Session session = null; long count = 0; try { session = parkingSessionFactory.getSessionFactory().openSession(); Criteria criteria = session.createCriteria(Notice.class); User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); String role = user.getRole(); criteria.add(Restrictions.eq("author", user)); criteria.add(Restrictions.ne(STATUS, NoticeStatus.DELETED.name())); criteria.setProjection(Projections.rowCount()); count = (long) criteria.uniqueResult(); } catch (Exception e) { LOGGER.error("unreadCount: error in unreadCount notfication", e); throw new OperationalException( HttpConstants.INTERNAL_SERVER_ERROR, ResponseConstants.ERROR_FETCHING_FROM_DB, HttpStatus.INTERNAL_SERVER_ERROR); } finally { if (session != null) { session.close(); } } return count; }
@SuppressWarnings("unchecked") public int countListIncomeReceipt(boolean includeVoided) { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(IncomeReceipt.class); if (!includeVoided) criteria.add(Restrictions.eq("voided", false)); Number rs = (Number) criteria.setProjection(Projections.rowCount()).uniqueResult(); return rs != null ? rs.intValue() : 0; }
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; }
/** * @see org.openmrs.api.db.ObsDAO#getObservationCount(java.util.List, java.util.List, * java.util.List, java.util.List, java.util.List, java.util.List, java.lang.Integer, * java.util.Date, java.util.Date, boolean, String) */ public Long getObservationCount( List<Person> whom, List<Encounter> encounters, List<Concept> questions, List<Concept> answers, List<PERSON_TYPE> personTypes, List<Location> locations, Integer obsGroupId, Date fromDate, Date toDate, List<ConceptName> valueCodedNameAnswers, boolean includeVoidedObs, String accessionNumber) throws DAOException { Criteria criteria = createGetObservationsCriteria( whom, encounters, questions, answers, personTypes, locations, null, null, obsGroupId, fromDate, toDate, valueCodedNameAnswers, includeVoidedObs, accessionNumber); criteria.setProjection(Projections.rowCount()); return (Long) criteria.list().get(0); }
@Override public Long verificarConflitoHorario(Horario model) { Criteria criteria = getSession().createCriteria(Horario.class); // Removendo da pesquisa o proprio registro quando for edição if (model.getId() != null && !model.getId().equals(0)) { List<Integer> listaIds = new ArrayList<Integer>(); listaIds.add(model.getId()); criteria.add(Restrictions.not(Restrictions.in("id", listaIds))); } criteria.add(Restrictions.eq("curso.id", model.getCurso().getId())); criteria.add( Restrictions.or( Restrictions.or( Restrictions.between( "datHoraInicio", model.getDatHoraInicio(), model.getDatHoraFim()), Restrictions.between( "datHoraFim", model.getDatHoraInicio(), model.getDatHoraFim())), Restrictions.and( Restrictions.and( Restrictions.le("datHoraInicio", model.getDatHoraInicio()), Restrictions.ge("datHoraFim", model.getDatHoraInicio())), Restrictions.and( Restrictions.le("datHoraInicio", model.getDatHoraFim()), Restrictions.ge("datHoraFim", model.getDatHoraFim()))))); criteria.setProjection(Projections.rowCount()); Long result = (Long) criteria.list().get(0); return result; }
/** * @see org.openmrs.api.db.ObsDAO#getObservationCount(java.util.List, java.util.List, * java.util.List, java.util.List, java.util.List, java.util.List, java.lang.Integer, * java.util.Date, java.util.Date, boolean) */ public Integer getObservationCount( List<Person> whom, List<Encounter> encounters, List<Concept> questions, List<Concept> answers, List<PERSON_TYPE> personTypes, List<Location> locations, Integer obsGroupId, Date fromDate, Date toDate, boolean includeVoidedObs) throws DAOException { Criteria criteria = createGetObservationsCriteria( whom, encounters, questions, answers, personTypes, locations, null, null, obsGroupId, fromDate, toDate, includeVoidedObs); criteria.setProjection(Projections.rowCount()); return (Integer) criteria.list().get(0); }
@SuppressWarnings({"unchecked", "rawtypes"}) protected int countCriteriaResult(final Criteria c) { CriteriaImpl impl = (CriteriaImpl) c; Projection projection = impl.getProjection(); ResultTransformer transformer = impl.getResultTransformer(); List<CriteriaImpl.OrderEntry> orderEntries = null; try { orderEntries = (List<CriteriaImpl.OrderEntry>) ReflectionUtils.getFieldValue(impl, "orderEntries"); ReflectionUtils.setFieldValue(impl, "orderEntries", new ArrayList()); } catch (Exception e) { logger.error("", e); } int totalCount = (Integer) c.setProjection(Projections.rowCount()).uniqueResult(); c.setProjection(projection); if (projection == null) { c.setResultTransformer(CriteriaSpecification.ROOT_ENTITY); } if (transformer != null) { c.setResultTransformer(transformer); } try { ReflectionUtils.setFieldValue(impl, "orderEntries", orderEntries); } catch (Exception e) { logger.error("", e); } return totalCount; }
@Override public Long getTotalCount(Reply model) { Criteria criteria = getCurrentSession().createCriteria(Reply.class); criteria.createAlias("potential", "potential", CriteriaSpecification.LEFT_JOIN); criteria.createAlias( "potentialStuStatus", "potentialStuStatus", CriteriaSpecification.LEFT_JOIN); criteria.createAlias("user", "user", CriteriaSpecification.LEFT_JOIN); if (model != null && model.getPotential().getPotentialId() != null) { criteria.add(Restrictions.eq("potential.potentialId", model.getPotential().getPotentialId())); } if (model != null && model.getPotentialStuStatus() != null && model.getPotentialStuStatus().getPotentialStuStatusId() != null) { criteria.add( Restrictions.eq( "potentialStuStatus.potentialStuStatusId", model.getPotentialStuStatus().getPotentialStuStatusId())); } if (model != null && model.getReplyDate() != null) { criteria.add(Restrictions.eq("replyDate", model.getReplyDate())); } if (model != null && model.getNextReplyDate() != null) { criteria.add(Restrictions.eq("nextReplyDate", model.getNextReplyDate())); } criteria.setProjection(Projections.rowCount()); return new Long(criteria.uniqueResult().toString()); }
@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()); }
/** * 使用指定查询对象进行分页查询. * * @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); }
/** * 判断对象某些属性的值在数据库中不存在重复. * * @param entityClass 类型 * @param entity 指定的实体 * @param names 在POJO里不能重复的属性列表,以逗号分割 如"name,loginid,password" * @return 包含重复的内容返回true,否则返回false */ public boolean isGenericNotUnique(Class entityClass, Object entity, String names) { Assert.hasText(names); Criteria criteria = getEntityCriteria(entityClass).setProjection(Projections.rowCount()); String[] nameList = names.split(","); try { // 循环加入 for (String name : nameList) { criteria.add(Restrictions.eq(name, PropertyUtils.getProperty(entity, name))); } // 以下代码为了如果是update的情况,排除entity自身. // 通过Hibernate的MetaData接口取得主键名 String idPropertyName = getSessionFactory().getClassMetadata(entity.getClass()).getIdentifierPropertyName(); if (idPropertyName != null) { // 通过反射取得entity的主键值 Object id = PropertyUtils.getProperty(entity, idPropertyName); // 如果id!=null,说明对象已存在,该操作为update,加入排除自身的判断 if (id != null) criteria.add(Restrictions.not(Restrictions.eq(idPropertyName, id))); } } catch (IllegalAccessException e) { logger.error("Error when reflection on entity", e); return false; } catch (InvocationTargetException e) { logger.error("Error when reflection on entity", e); return false; } catch (NoSuchMethodException e) { logger.error("Error when reflection on entity", e); return false; } return (Integer) criteria.uniqueResult() > 0; }
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; }
/** * 分页查询函数,使用已设好查询条件与排序的<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); }
@SuppressWarnings("unchecked") public static boolean hasSemaineWithVacation(int id) { Session session = PilotageSession.getCurrentSession(); Planning_Vacation pv = (Planning_Vacation) session.load(Planning_Vacation.class, id); List<Long> results = (List<Long>) session .createCriteria(Planning_Semaine.class) .add( Restrictions.or( Restrictions.eq("lundi", pv), Restrictions.or( Restrictions.eq("mardi", pv), Restrictions.or( Restrictions.eq("mercredi", pv), Restrictions.or( Restrictions.eq("jeudi", pv), Restrictions.or( Restrictions.eq("vendredi", pv), Restrictions.or( Restrictions.eq("samedi", pv), Restrictions.eq("dimanche", pv)))))))) .setProjection(Projections.rowCount()) .list(); session.getTransaction().commit(); if (results != null && results.size() > 0 && results.get(0) > 0) { return true; } else { return false; } }
@Override public Long countParceirosInscritos( Integer idCursoSelecionado, Integer idGradeOficina, List<Integer> idsParceiros) { List<Integer> idsStatus = new ArrayList<Integer>(); idsStatus.add(Status.CANCELADO); idsStatus.add(Status.AGUARDANDO_VAGA_PRIORIDADE); idsStatus.add(Status.AGUARDANDO_VAGA); Criteria criteria = getSession().createCriteria(InscricaoGrade.class); criteria.createAlias("inscricaoCurso", "ic"); criteria.createAlias("ic.curso", "c"); criteria.add(Restrictions.eq("c.id", idCursoSelecionado)); criteria.createAlias("ic.ultimoStatus", "us"); criteria.createAlias("us.status", "s"); criteria.add(Restrictions.not(Restrictions.in("s.id", idsStatus))); criteria.createAlias("gradeOficina", "go"); criteria.add(Restrictions.eq("go.id", idGradeOficina)); if (idsParceiros != null && !idsParceiros.isEmpty()) { criteria.createAlias("ic.candidato", "cand"); criteria.add(Restrictions.in("cand.id", idsParceiros)); } criteria.setProjection(Projections.rowCount()); Long result = (Long) criteria.list().get(0); return result; }
@Override public Long countConceptsAlignedToExtThes(String idThesaurus) { DetachedCriteria alignmentCriteria = DetachedCriteria.forClass(Alignment.class, "al") .add(Restrictions.isNotNull("al.externalTargetThesaurus")) .setProjection( Projections.projectionList() .add(Projections.property(AL_SOURCE_CONCEPT_IDENTIFIER))); DetachedCriteria conceptCriteria = DetachedCriteria.forClass(ThesaurusConcept.class, "stc") .add(Restrictions.eq("stc.thesaurus.identifier", idThesaurus)) .setProjection( Projections.projectionList().add(Projections.property("stc.identifier"))); Criteria criteria = getCurrentSession() .createCriteria(ThesaurusConcept.class, "tc") .add( Restrictions.and( Subqueries.propertyIn(TC_IDENTIFIER, alignmentCriteria), Subqueries.propertyIn(TC_IDENTIFIER, conceptCriteria))) .setProjection(Projections.rowCount()); return (Long) criteria.list().get(0); }
// 获取Criteria查询数量 @SuppressWarnings("unchecked") private int criteriaResultTotalCount(Criteria criteria) { Assert.notNull(criteria, "criteria is required"); int criteriaResultTotalCount = 0; try { CriteriaImpl criteriaImpl = (CriteriaImpl) criteria; Projection projection = criteriaImpl.getProjection(); ResultTransformer resultTransformer = criteriaImpl.getResultTransformer(); List<OrderEntry> orderEntries = (List<OrderEntry>) ReflectionUtil.getFieldValue(criteriaImpl, "orderEntries"); ReflectionUtil.setFieldValue(criteriaImpl, "orderEntries", new ArrayList<OrderEntry>()); Integer totalCount = ((Long) criteriaImpl.setProjection(Projections.rowCount()).uniqueResult()).intValue(); if (totalCount != null) { criteriaResultTotalCount = totalCount; } criteriaImpl.setProjection(projection); if (projection == null) { criteriaImpl.setResultTransformer(CriteriaSpecification.ROOT_ENTITY); } if (resultTransformer != null) { criteriaImpl.setResultTransformer(resultTransformer); } ReflectionUtil.setFieldValue(criteriaImpl, "orderEntries", orderEntries); } catch (Exception e) { } return criteriaResultTotalCount; }
@Override public Long countConcepts(String idThesaurus) { Criteria criteria = getCurrentSession().createCriteria(ThesaurusConcept.class); criteria .add(Restrictions.eq(THESAURUS_IDENTIFIER, idThesaurus)) .setProjection(Projections.rowCount()); return (Long) criteria.list().get(0); }
@Override public Long countItems(String idThesaurus) { Criteria criteria = getCurrentSession().createCriteria(ThesaurusConceptGroup.class); criteria .add(Restrictions.eq("thesaurus.identifier", idThesaurus)) .setProjection(Projections.rowCount()); return (Long) criteria.list().get(0); }
public void testProjection() { Session s = openSession(); Transaction t = s.beginTransaction(); s.createCriteria(Item.class).setProjection(Projections.rowCount()).uniqueResult(); s.createCriteria(Item.class).uniqueResult(); t.commit(); s.close(); }
@Override public <T extends GettableById> Number count(Class<T> currentClass, Criterion... restrictions) { validateTransaction(); Criteria criteria = getSession().createCriteria(currentClass); criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); criteria.setProjection(Projections.rowCount()); for (Criterion restriction : restrictions) criteria.add(restriction); return ((Number) criteria.uniqueResult()); }
public long getNumQuestions(Source source) { Criteria crit = session().createCriteria(Question.class); crit.createAlias("source", "s"); crit.add(Restrictions.eq("s.id", source.getId())); crit.setProjection(Projections.rowCount()); return (long) crit.uniqueResult(); }
@Transactional(readOnly = true) public int mapCount(final int instanceID) throws SerializationException { final Criteria crit = getBiDirectionalMapCriteria(instanceID); crit.setProjection(Projections.rowCount()); final Long result = (Long) crit.uniqueResult(); return result.intValue(); }
/** * 按属性统计记录数 * * @param property * @param value * @return */ public int countByProperty(String property, Object value) { Assert.hasText(property); Assert.notNull(value); return ((Number) (createCriteria(Restrictions.eq(property, value)) .setProjection(Projections.rowCount()) .uniqueResult())) .intValue(); }
/** * 根据对象类型和Session对象取得查询数量的Criteria对象 * * @param clazz * @param session * @return Criteria */ public Criteria getCountCriteria(Class<?> clazz, Session session) { Criteria criteria = session.createCriteria(clazz); for (int i = 0; i < criterionList.size(); i++) { Criterion criterion = criterionList.get(i); criteria.add(criterion); } criteria.setProjection(Projections.rowCount()); return criteria; }
public Long getQuantidade(Class<? extends Segurado> klass, String situacao) { Criteria criteria = HibernateUtil.currentSession().createCriteria(klass); criteria .add(Expression.eq("situacao.descricao", situacao)) .setProjection(Projections.rowCount()); return (Long) criteria.uniqueResult(); }