/** * Perform a search over all child and sub orgs within the given organisation * * <p>If a search query is given it will be split by space and the key words searched in the * title, orgid, address, addressLine2 and postcode fields. * * @param q - search query, which is a space seperated list of key words. Optional * @param organisation - search is for orgs inside this * @param orgType - optional, if given results are limited to organisations of this type * @param session * @return */ public static List<Organisation> search( String q, Organisation organisation, OrgType orgType, Session session) { Criteria crit = session.createCriteria(Organisation.class); crit.setCacheable(true); Disjunction notDeleted = Restrictions.disjunction(); notDeleted.add(Restrictions.isNull("deleted")); notDeleted.add(Restrictions.eq("deleted", Boolean.FALSE)); crit.add(notDeleted); if (q != null) { String[] arr = q.split(" "); Conjunction con = Restrictions.conjunction(); for (String queryPart : arr) { Disjunction dis = Restrictions.disjunction(); String s = "%" + queryPart + "%"; dis.add(Restrictions.ilike("title", s)); dis.add(Restrictions.ilike("orgId", s)); dis.add(Restrictions.ilike("address", s)); dis.add(Restrictions.ilike("addressLine2", s)); dis.add(Restrictions.ilike("postcode", s)); con.add(dis); } crit.add(con); } if (orgType != null) { crit.add(Restrictions.eq("orgType", orgType)); } // TODO: add other properties like address Criteria critParentLink = crit.createCriteria("parentOrgLinks"); critParentLink.add(Restrictions.eq("owner", organisation)); crit.addOrder(Order.asc("title")); return DbUtils.toList(crit, Organisation.class); }
/* * (non-Javadoc) * * @see com.pfchoice.core.dao.ICDMeasureDao#getPage(int, int, * java.lang.String, java.lang.String, java.lang.String) */ @Override public Pagination getPage( final int pageNo, final int pageSize, final String sSearch, final String sort, final String sortdir) { Criteria crit = createCriteria(); if (sSearch != null && !"".equals(sSearch)) { Disjunction or = Restrictions.disjunction(); or.add(Restrictions.ilike("code", "%" + sSearch + "%")) .add(Restrictions.ilike("description", "%" + sSearch + "%")) .add(Restrictions.ilike("hcc", "%" + sSearch + "%")) .add(Restrictions.ilike("rxhcc", "%" + sSearch + "%")); crit.add(or); } if (sort != null && !"".equals(sort)) { if (sortdir != null && !"".equals(sortdir) && "desc".equals(sortdir)) { crit.addOrder(Order.desc(sort)); } else { crit.addOrder(Order.asc(sort)); } } crit.add(Restrictions.eq("activeInd", 'Y')); return findByCriteria(crit, pageNo, pageSize); }
public List<Clients> getFromProxy(List<Clients> proxy) { Disjunction or = Restrictions.disjunction(); for (Clients pr : proxy) { or.add(Restrictions.eq("id", pr.getId())); } return sessionFactory.getCurrentSession().createCriteria(Clients.class).add(or).list(); }
public static Criterion sameEnterprise(final Enterprise enterprise) { Disjunction filterDisjunction = Restrictions.disjunction(); filterDisjunction.add(Restrictions.eq(Role.ENTERPRISE_PROPERTY, enterprise)); return filterDisjunction; }
public int getNumDocuments(String folderId) { DmFolder folder = null; if (folderId != null) { folder = new DmFolder(); folder.setId(folderId); } if (folder != null) { Disjunction disjunction = Restrictions.disjunction(); disjunction.add(Restrictions.isNull("docApproval.id")); disjunction.add( Restrictions.ne("docApproval.status", ApplicationConstants.APPROVAL_STATUS_REJECTED)); Criteria crit = getSession().createCriteria(DmDocumentFolder.class); crit.createAlias("document", "docInfo"); crit.createAlias("docInfo.approval", "docApproval", CriteriaSpecification.LEFT_JOIN); crit.add(Restrictions.eq("folder", folder)); // crit.add(Restrictions.eq("docInfo.approved", true)); crit.add(disjunction); return crit.list().size(); } return 0; }
private Criterion filterExactlyBy(final String filter) { Disjunction filterDisjunction = Restrictions.disjunction(); filterDisjunction.add(Restrictions.like(Role.NAME_PROPERTY, filter)); return filterDisjunction; }
/** * 解析一个条件成为符合Hibernate的Criteria的实例条件 * * @param condition * @param criteria * @return */ public static Criteria parseConditionToCriteria( Condition condition, Criteria criteria, Class<?> persistentClass) { // 创建一个Or的连接条件集合 Disjunction disjunction = Restrictions.disjunction(); parseConditionToJunction(condition, disjunction, persistentClass); return criteria.add(disjunction); }
public int getUserDetailsCountBySessionId(String searchq, Long sessionPK) { Session session = getSession(); session.getTransaction().begin(); int totalRowCount = 0; Criteria criteria = session.createCriteria(BrowserDetails.class, "browserDetails"); criteria.createAlias("browserDetails.sessionDetails", "sessionDetails"); criteria.createAlias("browserDetails.deviceDetails", "deviceDetails"); criteria.createAlias("browserDetails.eventDetails", "eventDetails"); criteria.add(Restrictions.eq("sessionDetails.SID", sessionPK)); criteria.setProjection(Projections.count("eventDetails.EID")); if (!searchq.isEmpty()) { criteria.add( Restrictions.disjunction() .add(Restrictions.ilike("deviceDetails.deviceName", searchq, MatchMode.ANYWHERE)) .add(Restrictions.ilike("browserName", searchq, MatchMode.ANYWHERE)) .add(Restrictions.ilike("eventDetails.eventName", searchq, MatchMode.ANYWHERE)) .add(Restrictions.ilike("eventDetails.orientation", searchq, MatchMode.ANYWHERE))); } Long value = (Long) criteria.uniqueResult(); totalRowCount = Integer.valueOf(value.intValue()); session.getTransaction().commit(); session.close(); return totalRowCount; }
public static Vector<Person> searchPerson(String keyword) { Session session = sf.openSession(); Criteria criteria = session.createCriteria(Person.class); keyword = keyword.trim(); Disjunction or = Restrictions.disjunction(); or.add(Restrictions.like("name", "%" + keyword + "%")); or.add(Restrictions.like("sex", "%" + keyword + "%")); or.add(Restrictions.like("born", "%" + keyword + "%")); or.add(Restrictions.like("year", "%" + keyword + "%")); or.add(Restrictions.like("day", "%" + keyword + "%")); criteria.add(or); Vector vt = new Vector(); List result = new Vector<Person>(); result = criteria.list(); for (Object o : result) { Person person = (Person) o; Vector temp = new Vector(); temp.add(person.getName()); temp.add(person.getSex()); temp.add(person.getBorn()); temp.add(person.getYear()); temp.add(person.getDay()); temp.add(person.getId()); temp.add(person.getIsdirector()); temp.add(person.getIsstar()); vt.add(temp); } return vt; }
public static List<Object> getListObjectsByOrs( Class myClass, String strFieldName, List listArgs, String strDbName) { Session session = null; Transaction tx = null; List result = null; if (listArgs != null && listArgs.size() > 0) { try { session = getSessionDude(strDbName); // sessionFactory.getCurrentSession(); tx = session.beginTransaction(); Criteria criteria = session.createCriteria(myClass); Disjunction disj; Property property = Property.forName(strFieldName); if (listArgs != null && listArgs.size() > 0) { disj = Restrictions.disjunction(); for (Object strArgs : listArgs) { disj.add(property.eq(strArgs)); } tx.commit(); result = criteria.add(disj).list(); } } finally { if (session != null && session.isOpen()) { session.close(); } } } return result; }
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; }
@SuppressWarnings("unchecked") @Override public Collection<FuncionarioAreaTrabajoDTO> consultarFuncionarioAreaTrabajoPorAreaTrabajo( Integer codigoAreaTrabajo, String userId, Integer codigoCompania, String usuarioSesion) throws SICException { try { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(FuncionarioAreaTrabajoDTO.class); criteria.setProjection( Projections.projectionList() .add(Projections.property("usuarioDTO.userId"), "funcionarioDTO.usuarioDTO.userId") .add( Projections.property("usuarioDTO.userCompleteName"), "funcionarioDTO.usuarioDTO.userCompleteName") .add( Projections.property("usuarioDTO.userName"), "funcionarioDTO.usuarioDTO.userName") .add( Projections.property("areaTrabajoDTO.nombreAreaTrabajo"), "areaTrabajoDTO.nombreAreaTrabajo") .add(Projections.property("id.codigoCompania"), "id.codigoCompania") .add(Projections.property("id.codigoFuncionario"), "id.codigoFuncionario") .add(Projections.property("id.codigoAreaTrabajo"), "id.codigoAreaTrabajo")); criteria.createAlias("funcionarioDTO", "funcionarioDTO"); criteria.createAlias("funcionarioDTO.usuarioDTO", "usuarioDTO"); criteria.createAlias("areaTrabajoDTO", "areaTrabajoDTO"); criteria.add(Restrictions.eq("estado", SICConstantes.ESTADO_ACTIVO_LITERAL)); criteria.add( Restrictions.eq("funcionarioDTO.estadoFuncionario", SICConstantes.ESTADO_ACTIVO_LITERAL)); criteria.add( Restrictions.eq("areaTrabajoDTO.estadoAreaTrabajo", SICConstantes.ESTADO_ACTIVO_LITERAL)); criteria.add(Restrictions.eq("id.codigoCompania", codigoCompania)); criteria.add(Restrictions.eq("areaTrabajoDTO.id.codigoAreaTrabajo", codigoAreaTrabajo)); criteria.add(Restrictions.ne("usuarioDTO.userName", usuarioSesion)); // si el usuario ingresa un nombre o usuario de un funcionario if (StringUtils.isNotEmpty(userId)) { Disjunction disjunction = Restrictions.disjunction(); disjunction.add(Restrictions.ilike("usuarioDTO.userName", userId, MatchMode.ANYWHERE)); disjunction.add( Restrictions.ilike("usuarioDTO.userCompleteName", userId, MatchMode.ANYWHERE)); criteria.add(disjunction); } criteria.setResultTransformer(new DtoResultTransformer(FuncionarioAreaTrabajoDTO.class)); Collection<FuncionarioAreaTrabajoDTO> funcionarioAreaTrabajoDTOCol = criteria.list(); return funcionarioAreaTrabajoDTOCol; } catch (HibernateException e) { throw new SICException("Error consultarFuncionarioAreaTrabajoPorAreaTrabajo: ", e); } catch (Exception e) { throw new SICException("Error consultarFuncionarioAreaTrabajoPorAreaTrabajo ", e); } }
public static Criterion in(String propertyName, Collection<?> values, int maxLength) { if (maxLength < 1) throw new IllegalArgumentException("maxLength must be positive"); Disjunction result = Restrictions.disjunction(); for (Collection<?> part : partitionCollection(values, maxLength)) { result.add(Restrictions.in(propertyName, part)); } return result; }
/** * 解析一个条件成为符合Hibernate的Junction的实例条件 * * @param condition * @param junction */ public static void parseConditionToJunction( Condition condition, Junction junction, Class<?> persistentClass) { // 子条件 List<Condition> subConditions = condition.getSubConditions(); // 有子条件则进行遍历获取最终的条件 if (null != subConditions && !subConditions.isEmpty()) { // 子条件当中的and条件集合 List<Condition> andConditions = condition.getAndConditions(); if (null != andConditions && !andConditions.isEmpty()) { // 创建一个and条件集合 Conjunction conj = Restrictions.conjunction(); // 添加到父条件中 junction.add(conj); for (Condition andCondition : andConditions) { /* * 把每个条件看做是一个大的条件(包含 and 和 or 2个部分), * 然后使用disjunction连接条件集合来组合这个大条件的(and项 和 or项); * 因为and项和or项都已经被分为2个部分 * ,而且又是用disjunction来组合,所以可以保证一个大条件只会被or连接符分隔成2个部分 */ Disjunction dj = Restrictions.disjunction(); conj.add(dj); parseConditionToJunction(andCondition, dj, persistentClass); } } // 子条件当中的or条件集合 List<Condition> orConditions = condition.getOrConditions(); if (null != orConditions && !orConditions.isEmpty()) { // 创建一个or条件集合 Disjunction disj = Restrictions.disjunction(); // 添加到父条件中 junction.add(disj); for (Condition orCondition : orConditions) { // 这里的实现原理与上面的andCondition的处理相同 Disjunction dj = Restrictions.disjunction(); disj.add(dj); parseConditionToJunction(orCondition, dj, persistentClass); } } } else { // 条件为最终条件,转换为符合Hibernate的条件,然后条件到条件集合中 junction.add(condition.getCriterion(persistentClass)); } }
@Override public List<Daily> getFromProxy(List<Daily> proxy) { Disjunction or = Restrictions.disjunction(); for (Daily pr : proxy) { or.add(Restrictions.eq("id", pr.getId())); } return sessionFactory.getCurrentSession().createCriteria(Daily.class).add(or).list(); }
public boolean exist(Usuario usuario) { Criteria criteria = this.getSession().createCriteria(Usuario.class); Disjunction ou = Restrictions.disjunction(); ou.add(Restrictions.eq("numeroDaCasa", usuario.getNumeroDaCasa())); ou.add(Restrictions.ilike("email", usuario.getEmail(), MatchMode.ANYWHERE)); return criteria.add(ou).list().size() > 0; }
public static Profile find(String name, Session session) { Criteria crit = session.createCriteria(Profile.class); crit.setCacheable(true); crit.add( Restrictions.disjunction() .add(Restrictions.eq("name", name)) .add(Restrictions.eq("email", name))); return DbUtils.unique(crit); }
private static void setAuthorizedSiteData(DetachedCriteria criteria, List<SiteData> sites) { Disjunction disjunction = Restrictions.disjunction(); for (SiteData sd : sites) { Conjunction con = new Conjunction(); con.add(Restrictions.eq("dpSiteName", sd.getSiteName())); con.add(Restrictions.eq("project", sd.getCollection())); disjunction.add(con); } criteria.add(disjunction); }
@Override public void buildUnordered(Criteria criteria) { // Type check if (showEventTypesM.getObject().size() < numberOfEventTypes) criteria.add(Restrictions.in("type", showEventTypesM.getObject())); else log.debug("Not filtering by event type"); criteria.createAlias("user", "user"); // Site Check List<Site> siteList = showSitesM.getObject(); if (siteList.size() < numberOfSites || inAPeriod.getObject()) { criteria.createAlias("user.periods", "period", JoinType.LEFT_OUTER_JOIN); Disjunction siteRestriction = Restrictions.disjunction(); if (!inAPeriod.getObject()) siteRestriction.add(Restrictions.isEmpty("user.periods")); // Show users with no periods if (!siteList.isEmpty()) siteRestriction.add( Restrictions.in("period.site", siteList)); // Show users with matching periods if (inAPeriod.getObject() && siteList.isEmpty()) { siteRestriction.add(Restrictions.idEq(-1L)); // Halt query early; don't show anyone. criteria.setMaxResults(0); } criteria.add(siteRestriction); } else { log.debug("Not filtering by period/site"); } if (fromDateM.getObject() != null && toDateM.getObject() != null) { Date startDate = midnightStart(fromDateM.getObject()); Date endDate = midnightEnd(toDateM.getObject()); log.debug("Considering events between {} and {}", startDate, endDate); criteria.add(Restrictions.between("insertTime", startDate, endDate)); } // set permission check if (showPermissionUsers.getObject()) { criteria.add(Restrictions.eq("user.permission", true)); } // Also load ResponseData elements in the same query, to avoid thousands of subsequent // queries. criteria.setFetchMode("responseData", FetchMode.JOIN); // The join with periods results in multiple rows for multi-period users. // Unfortunately, this confuses the dataprovider, which still counts the duplicates // and therefore doesn't return a full page full of items each time. criteria.setResultTransformer( CriteriaSpecification .DISTINCT_ROOT_ENTITY); // Remove duplicate rows as a result of the INNER JOIN }
private <T extends ResourceManagementHB> void createRasdManagement( Session session, int[] resourceTypes, Class<T> cl) throws PersistenceException { VirtualappHB virtualAppHB = (VirtualappHB) session.get("VirtualappExtendedHB", vApp.getIdVirtualApp()); VirtualDataCenterHB virtualDataCenterHB = virtualAppHB.getVirtualDataCenterHB(); Disjunction virtualAppDisjuction = Restrictions.disjunction(); virtualAppDisjuction.add(Restrictions.eq("idVirtualApp", virtualAppHB.getIdVirtualApp())); ArrayList<NodeHB> nodes = (ArrayList<NodeHB>) session.createCriteria(NodeHB.class).add(virtualAppDisjuction).list(); VirtualmachineHB virtualMachineHB; ArrayList<ResourceAllocationSettingData> rasds; ResourceManagementHB resourceManagement = null; Timestamp timestamp = new Timestamp(new GregorianCalendar().getTimeInMillis()); for (NodeHB node : nodes) { if (node.getType() == NodeTypeEnum.VIRTUAL_IMAGE) { NodeVirtualImageHB nodeVirtualImage = (NodeVirtualImageHB) node; virtualMachineHB = nodeVirtualImage.getVirtualMachineHB(); if (virtualMachineHB != null) { for (int resourceType : resourceTypes) { rasds = getRasds(session, resourceType); for (ResourceAllocationSettingData rasd : rasds) { try { resourceManagement = cl.newInstance(); } catch (Exception e) { throw new PersistenceException( "Unable to create a new instance of " + cl.getName()); } resourceManagement.setIdResourceType(rasd.getResourceType() + ""); resourceManagement.setRasd(rasd); resourceManagement.setVirtualApp(virtualAppHB); resourceManagement.setVirtualMachine(virtualMachineHB); resourceManagement.setVirtualDataCenter(virtualDataCenterHB); session.saveOrUpdate(resourceManagement); resourceManagementHBs.add(resourceManagement); } } } } } }
@SuppressWarnings("unchecked") public List<T> findByText(String searchText, String sortProp, boolean ascending) { List<Column> cols = HibernateUtil.getColumns(persistentClass.getName(), excludeDefault); Iterator<Column> it = cols.iterator(); Criteria crit = getSession().createCriteria(persistentClass); Disjunction disjunction = Restrictions.disjunction(); while (it.hasNext()) { Column col = it.next(); String colName = col.getName(); String propName = HibernateUtil.convertToHibernatePropertyName(colName); String type = HibernateUtil.getPropertyType(persistentClass, propName); if (type != null) { if (type.equals("integer") || type.equals("smallint")) { try { Integer.valueOf(searchText); Criterion criterium = Restrictions.eq(propName, Integer.valueOf(searchText)); disjunction.add(criterium); } catch (NumberFormatException ex) { } } else if (type.equals("string")) { Criterion criterium = Restrictions.ilike(propName, searchText, MatchMode.ANYWHERE); disjunction.add(criterium); } /*else if(type.equals("timestamp")){ Disjunction dis = Restrictions.disjunction(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); try { dis.add(Restrictions.eq(propName, format.parse(searchText))); } catch (ParseException e) { } try{ Integer.valueOf(searchText); dis.add(Restrictions.sqlRestriction( "YEAR(DATE("+colName+"))="+searchText+ " OR " + "MONTH(DATE("+colName+"))="+searchText+ " OR " + "DAY(DATE("+colName+"))="+searchText)); } catch(NumberFormatException ex) { } disjunction.add(dis); }*/ } } crit.add(disjunction); if (sortProp != null && !sortProp.equals("")) { if (ascending) crit.addOrder(Order.asc(sortProp)); else crit.addOrder(Order.desc(sortProp)); } return crit.list(); }
/** * @see * org.openmrs.module.radiology.RadiologyService#getActiveRadiologyReportByRadiologyOrder(RadiologyOrder) */ @Override public RadiologyReport getActiveRadiologyReportByRadiologyOrder(RadiologyOrder radiologyOrder) { return (RadiologyReport) sessionFactory .getCurrentSession() .createCriteria(RadiologyReport.class) .add(Restrictions.eq("radiologyOrder", radiologyOrder)) .add( Restrictions.disjunction() .add(Restrictions.eq("reportStatus", RadiologyReportStatus.CLAIMED)) .add(Restrictions.eq("reportStatus", RadiologyReportStatus.COMPLETED))) .list() .get(0); }
/** * Méthode en charge de traiter le critère posé sur numéro IPP ou nom ou prénom. * * @param criteria Criteria Hibernate. * @param crit Critère de recherche Patient. */ private void handleCriteriaNumeroIppOrNomOrPrenom( final Criteria criteria, final PatientSearchCriteria crit) { if (StringUtils.isNotEmpty(crit.getNumeroIppOrNomOrPrenom())) { final Disjunction dij = Restrictions.disjunction(); // Numéro interne CriteriaMakerUtils.addSqlCritere(dij, "this_.numeroIpp", crit.getNumeroIppOrNomOrPrenom()); // Nom CriteriaMakerUtils.addSqlCritere(dij, "this_.nom", crit.getNumeroIppOrNomOrPrenom()); // Promoteur CriteriaMakerUtils.addSqlCritere(dij, "this_.prenom", crit.getNumeroIppOrNomOrPrenom()); criteria.add(dij); } }
@Override public List<Cliente> listarPorNomes( String codigoPequisa, String nomePequisa, String placaPequisa, String ufPequisa, String situacao) { Criteria c = getSession().createCriteria(Cliente.class); Disjunction d = Restrictions.disjunction(); if (codigoPequisa != null && !codigoPequisa.equals("")) { d.add(Restrictions.ilike("codigo", codigoPequisa, MatchMode.ANYWHERE)); } if (nomePequisa != null && !nomePequisa.equals("")) { d.add(Restrictions.ilike("nome", nomePequisa, MatchMode.ANYWHERE)); d.add(Restrictions.ilike("razaoSocial", nomePequisa, MatchMode.ANYWHERE)); } if (ufPequisa != null && !ufPequisa.equals("") && !ufPequisa.equals("---")) { c.createAlias("enderecoPrimario", "endp"); c.createAlias("enderecoSecundario", "ends"); d.add(Restrictions.eq("endp.uf", ufPequisa)); d.add(Restrictions.eq("ends.uf", ufPequisa)); } if (placaPequisa != null && !placaPequisa.equals("")) { c.createAlias("veiculos", "vei"); d.add(Restrictions.ilike("vei.placa", placaPequisa, MatchMode.ANYWHERE)); } if (situacao != null && !situacao.equals("Todos")) { c.createAlias("contratos", "con"); for (SituacaoContrato s : SituacaoContrato.values()) { if (s.getValor().equals(situacao)) { d.add(Restrictions.eq("con.situacao", s)); } } } c.setFetchMode("contratos", FetchMode.SELECT); c.add(d); List<Cliente> clis = c.list(); for (Cliente cliente : clis) { Hibernate.initialize(cliente.getContratos()); } return clis; }
public Map<String, Object> lista(Map<String, Object> params) { log.debug("Buscando lista de Temporada Colportor con params {}", params); if (params == null) { params = new HashMap<>(); } if (!params.containsKey(Constantes.CONTAINSKEY_MAX)) { params.put(Constantes.CONTAINSKEY_MAX, 10); } else { params.put( Constantes.CONTAINSKEY_MAX, Math.min((Integer) params.get(Constantes.CONTAINSKEY_MAX), 100)); } if (params.containsKey(Constantes.CONTAINSKEY_PAGINA)) { Long pagina = (Long) params.get(Constantes.CONTAINSKEY_PAGINA); Long offset = (pagina - 1) * (Integer) params.get(Constantes.CONTAINSKEY_MAX); params.put(Constantes.CONTAINSKEY_OFFSET, offset.intValue()); } if (!params.containsKey(Constantes.CONTAINSKEY_OFFSET)) { params.put(Constantes.CONTAINSKEY_OFFSET, 0); } Criteria criteria = currentSession().createCriteria(TemporadaColportor.class); Criteria countCriteria = currentSession().createCriteria(TemporadaColportor.class); if (params.containsKey(Constantes.CONTAINSKEY_FILTRO)) { String filtro = (String) params.get(Constantes.CONTAINSKEY_FILTRO); filtro = "%" + filtro + "%"; Disjunction propiedades = Restrictions.disjunction(); propiedades.add(Restrictions.ilike("status", filtro)); criteria.add(propiedades); countCriteria.add(propiedades); } if (params.containsKey(Constantes.CONTAINSKEY_ORDER)) { String campo = (String) params.get(Constantes.CONTAINSKEY_ORDER); if (params.get(Constantes.CONTAINSKEY_SORT).equals(Constantes.CONTAINSKEY_SORT)) { criteria.addOrder(Order.desc(campo)); } else { criteria.addOrder(Order.asc(campo)); } } if (!params.containsKey(Constantes.CONTAINSKEY_REPORTE)) { criteria.setFirstResult((Integer) params.get(Constantes.CONTAINSKEY_OFFSET)); criteria.setMaxResults((Integer) params.get(Constantes.CONTAINSKEY_MAX)); } params.put(Constantes.CONTAINSKEY_TEMPORADACOLPORTORES, criteria.list()); countCriteria.setProjection(Projections.rowCount()); params.put(Constantes.CONTAINSKEY_CANTIDAD, (Long) countCriteria.list().get(0)); return params; }
public static List getListObjectsByAnds_Ors( Class myClass, Map<String, Object> mapArgsAnds, String strFieldName, List listArgsOrs, String strDbName) { List resutl = null; Session session = null; Transaction tx = null; try { session = getSessionDude(strDbName); // sessionFactory.getCurrentSession(); tx = session.beginTransaction(); Criteria criteria = session.createCriteria(myClass); if (mapArgsAnds != null && mapArgsAnds.size() > 0) { Iterator iter = mapArgsAnds.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, Object> pair = (Map.Entry<String, Object>) iter.next(); criteria.add(Restrictions.eq(pair.getKey(), pair.getValue())); } } if (listArgsOrs != null && listArgsOrs.size() > 0) { Disjunction disj; Property property = Property.forName(strFieldName); if (listArgsOrs != null && listArgsOrs.size() > 0) { disj = Restrictions.disjunction(); for (Object strArgs : listArgsOrs) { disj.add(property.eq(strArgs)); } resutl = criteria.add(disj).list(); } tx.commit(); if (resutl == null) { resutl = criteria.list(); } } } finally { if (session != null && session.isOpen()) { session.close(); } } return resutl; }
private void addStatusDisjunctionRestriction( Criteria criteria, List<PaperRecordMergeRequest.Status> statusList) { if (statusList.size() == 1) { criteria.add(Restrictions.eq("status", statusList.get(0))); } else { Disjunction statusDisjunction = Restrictions.disjunction(); for (PaperRecordMergeRequest.Status status : statusList) { statusDisjunction.add(Restrictions.eq("status", status)); } criteria.add(statusDisjunction); } }
@Override public int obtenhaQuantidadePorUF(UF estado) { Criteria c = getSession().createCriteria(Cliente.class); c.createAlias("enderecoPrimario", "endp"); c.createAlias("enderecoSecundario", "ends"); Disjunction d = Restrictions.disjunction(); d.add(Restrictions.eq("endp.uf", estado.getSigla())); d.add(Restrictions.eq("ends.uf", estado.getSigla())); c.setProjection(Projections.count("codigo")); c.add(d); return (int) c.uniqueResult(); }
private void addLocationRestriction(Criteria criteria, Location medicalRecordLocation) { // in our current workflow, both paper records should always have the same record location, but, // just in case, // we fetch any merge reqeusts where *either* of the records are associated with the specified // record location criteria.createAlias("preferredPaperRecord", "ppr"); criteria.createAlias("notPreferredPaperRecord", "nppr"); Disjunction locationDisjunction = Restrictions.disjunction(); locationDisjunction.add(Restrictions.eq("ppr.recordLocation", medicalRecordLocation)); locationDisjunction.add(Restrictions.eq("nppr.recordLocation", medicalRecordLocation)); criteria.add(locationDisjunction); }
/** * Gets a lists of ResourceAllocationSettingData that correspond to a particular resource type * * @param session * @param resourceType * @return */ private static ArrayList<ResourceAllocationSettingData> getRasds( Session session, int resourceType) { Disjunction disjunction = Restrictions.disjunction(); disjunction.add(Restrictions.eq("resourceType", resourceType)); ArrayList<ResourceAllocationSettingData> rasds = (ArrayList<ResourceAllocationSettingData>) session.createCriteria(ResourceAllocationSettingData.class).add(disjunction).list(); if (rasds == null) { rasds = new ArrayList<ResourceAllocationSettingData>(); } return rasds; }