@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); }
@Override public List<ThesaurusConcept> getPaginatedAvailableConceptsOfGroup( Integer startIndex, Integer limit, String groupId, String thesaurusId, Boolean onlyValidatedConcepts, String like) { DetachedCriteria dc = DetachedCriteria.forClass(ThesaurusConceptGroup.class, "gr"); dc.createCriteria("concepts", "tc", JoinType.RIGHT_OUTER_JOIN); dc.setProjection(Projections.projectionList().add(Projections.property("tc.identifier"))); dc.add(Restrictions.eq("gr.identifier", groupId)); Criteria criteria = selectPaginatedConceptsByAlphabeticalOrder(startIndex, limit); criteria.add(Subqueries.propertyNotIn("tc.identifier", dc)); selectThesaurus(criteria, thesaurusId); criteria.add( Restrictions.not( Restrictions.and( Restrictions.eq("topConcept", false), Restrictions.or( Restrictions.isNull("tc.parentConcepts"), Restrictions.isEmpty("tc.parentConcepts"))))); if (null != like) { conceptNameIsLike(criteria, like); } onlyValidatedConcepts(criteria, onlyValidatedConcepts); return criteria.list(); }
@SuppressWarnings("unchecked") // Hibernate public List<GeometryEntity> getGeometriesOrderedByTimestamp(DbQuery parameters) { Criteria criteria = session.createCriteria(SamplingGeometryEntity.class); DetachedCriteria filter = parameters.createDetachedFilterCriteria("pkid"); criteria.add(Subqueries.propertyIn(COLUMN_SERIES_PKID, filter)); criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); criteria.addOrder(Order.asc(COLUMN_TIMESTAMP)); parameters.addSpatialFilterTo(criteria, parameters); return (List<GeometryEntity>) criteria.list(); }
/** * Convenience method that adds an expression to the given <code>criteria</code> according to what * types of person objects is wanted * * @param criteria * @param personType * @return the given criteria (for chaining) */ private Criteria getCriteriaPersonModifier(Criteria criteria, List<PERSON_TYPE> personTypes) { if (personTypes.contains(PERSON_TYPE.PATIENT)) { DetachedCriteria crit = DetachedCriteria.forClass(Patient.class, "patient") .setProjection(Property.forName("patientId")); criteria.add(Subqueries.propertyIn("person.personId", crit)); } if (personTypes.contains(PERSON_TYPE.USER)) { DetachedCriteria crit = DetachedCriteria.forClass(User.class, "user").setProjection(Property.forName("userId")); criteria.add(Subqueries.propertyIn("person.personId", crit)); } if (personTypes.contains(PERSON_TYPE.PERSON)) { // all observations are already on person's. Limit to non-patient and non-users here? // criteria.createAlias("Person", "person"); // criteria.add(Restrictions.eqProperty("obs.person.personId", "person.personId")); } return criteria; }
public PaginatedList<Keyword> findKeywords( Keyword keyword, final boolean ignoreCase, final Order order, final Integer firstResult, final Integer maxResults) throws IllegalArgumentException { if (keyword == null) { throw new IllegalArgumentException("keyword cannot be null"); } final MatchMode matchMode = MatchMode.ANYWHERE; Example criterionKeyword = Example.create(keyword); criterionKeyword.enableLike(matchMode); if (ignoreCase) { criterionKeyword.ignoreCase(); } // Normally, Hibernate performs a left-outer join, when searching for // an object with collections using Criteria. This returns a ResultSet // that contains duplicate objects. In order to get a unique list of // Keywords with paginated support, we need to a nested query to find // distinct matching ids, then get the Keywords. The end result is a // subselect in the main query, but only one query is sent. DetachedCriteria dc = DetachedCriteria.forClass(Keyword.class); dc.add(criterionKeyword); dc.setResultTransformer(DISTINCT_ROOT_ENTITY); Conjunction conjunction = createTranslationConditions(keyword.getTranslations(), ignoreCase, matchMode); if (conjunction != null) dc.createCriteria(FIELD_TRANSLATIONS).add(conjunction); dc.setProjection(Projections.id()); Criteria criteria = getSession().createCriteria(Keyword.class); criteria.add(Subqueries.propertyIn(FIELD_ID, dc)); if (Order.desc == order) criteria.addOrder(desc(FIELD_KEYWORD)); else criteria.addOrder(asc(FIELD_KEYWORD)); if (firstResult != null) criteria.setFirstResult(firstResult); if (maxResults != null) criteria.setMaxResults(maxResults); final List<Keyword> criteriaList = criteria.list(); int maxListSize = 0; if (criteriaList.size() > 0) { maxListSize = calculateMaxListSize(criterionKeyword, conjunction); } return new PaginatedList<Keyword>(criteriaList, maxListSize); }
@Override public List<Salon> getByEquipoName(String equipoName) { Criterion crit1 = Restrictions.ilike("name", equipoName, MatchMode.ANYWHERE); DetachedCriteria subQuery = DetachedCriteria.forClass(Salon.class) .createCriteria("equipos") .add(Restrictions.or(crit1)) .setProjection(Projections.id()); Criteria mainCriteria = getSession() .createCriteria(Salon.class) .add(Subqueries.propertyIn("id", subQuery)) .setFetchMode("equipos", FetchMode.JOIN); return mainCriteria.list(); }
@Override public List<ThesaurusConcept> getConceptsAlignedToMyThes( String idThesaurus, int startIndex, int limit) { DetachedCriteria alignmentCriteria = DetachedCriteria.forClass(Alignment.class, "al") .add(Restrictions.eq("al.internalTargetThesaurus.identifier", idThesaurus)) .setProjection( Projections.projectionList() .add(Projections.property(AL_SOURCE_CONCEPT_IDENTIFIER))); Criteria criteria = getCurrentSession() .createCriteria(ThesaurusConcept.class, "tc") .add(Subqueries.propertyIn(TC_IDENTIFIER, alignmentCriteria)) .setFirstResult(startIndex) .setMaxResults(limit); return (List<ThesaurusConcept>) criteria.list(); }
public List<RecepcionMx> getRecepcionesByFiltro(FiltroMx filtro) { Session session = sessionFactory.getCurrentSession(); Soundex varSoundex = new Soundex(); Criteria crit = session.createCriteria(RecepcionMx.class, "recepcion"); crit.createAlias("recepcion.tomaMx", "tomaMx"); crit.createAlias("tomaMx.estadoMx", "estado"); // crit.createAlias("orden.idTomaMx", "tomaMx"); crit.createAlias("tomaMx.idNotificacion", "notifi"); // siempre se tomam las muestras que no estan anuladas crit.add( Restrictions.and( Restrictions.eq("tomaMx.anulada", false))); // y las ordenes en estado según filtro if (filtro.getCodEstado() != null) { if (filtro.getIncluirTraslados()) { crit.add( Restrictions.or(Restrictions.eq("estado.codigo", filtro.getCodEstado()).ignoreCase()) .add(Restrictions.or(Restrictions.eq("estado.codigo", "ESTDMX|TRAS")))); } else { crit.add( Restrictions.and( Restrictions.eq("estado.codigo", filtro.getCodEstado().toLowerCase()) .ignoreCase())); } } // se filtra por nombre y apellido persona if (filtro.getNombreApellido() != null) { // crit.createAlias("notifi.persona", "person"); String[] partes = filtro.getNombreApellido().split(" "); String[] partesSnd = filtro.getNombreApellido().split(" "); for (int i = 0; i < partes.length; i++) { try { partesSnd[i] = varSoundex.encode(partes[i]); } catch (IllegalArgumentException e) { partesSnd[i] = "0000"; e.printStackTrace(); } } for (int i = 0; i < partes.length; i++) { Junction conditGroup = Restrictions.disjunction(); conditGroup .add( Subqueries.propertyIn( "notifi.persona.personaId", DetachedCriteria.forClass(SisPersona.class, "person") .add( Restrictions.or( Restrictions.ilike( "person.primerNombre", "%" + partes[i] + "%")) .add( Restrictions.or( Restrictions.ilike( "person.primerApellido", "%" + partes[i] + "%")) .add( Restrictions.or( Restrictions.ilike( "person.segundoNombre", "%" + partes[i] + "%")) .add( Restrictions.or( Restrictions.ilike( "person.segundoApellido", "%" + partes[i] + "%")) .add( Restrictions.or( Restrictions.ilike( "person.sndNombre", "%" + partesSnd[i] + "%"))))))) .setProjection(Property.forName("personaId")))) .add( Subqueries.propertyIn( "notifi.solicitante.idSolicitante", DetachedCriteria.forClass(Solicitante.class, "solicitante") .add(Restrictions.ilike("solicitante.nombre", "%" + partes[i] + "%")) .setProjection(Property.forName("idSolicitante")))); crit.add(conditGroup); } } // se filtra por SILAIS if (filtro.getCodSilais() != null) { crit.createAlias("notifi.codSilaisAtencion", "silais"); crit.add( Restrictions.and(Restrictions.eq("silais.codigo", Long.valueOf(filtro.getCodSilais())))); } // se filtra por unidad de salud if (filtro.getCodUnidadSalud() != null) { crit.createAlias("notifi.codUnidadAtencion", "unidadS"); crit.add( Restrictions.and( Restrictions.eq("unidadS.codigo", Long.valueOf(filtro.getCodUnidadSalud())))); } // Se filtra por rango de fecha de toma de muestra if (filtro.getFechaInicioTomaMx() != null && filtro.getFechaFinTomaMx() != null) { crit.add( Restrictions.and( Restrictions.between( "tomaMx.fechaHTomaMx", filtro.getFechaInicioTomaMx(), filtro.getFechaFinTomaMx()))); } // Se filtra por rango de fecha de recepción if (filtro.getFechaInicioRecep() != null && filtro.getFechaFinRecep() != null) { crit.add( Restrictions.and( Restrictions.between( "recepcion.fechaHoraRecepcion", filtro.getFechaInicioRecep(), filtro.getFechaFinRecep()))); } // se filtra por tipo de muestra if (filtro.getCodTipoMx() != null) { crit.add( Restrictions.and( Restrictions.eq( "tomaMx.codTipoMx.idTipoMx", Integer.valueOf(filtro.getCodTipoMx())))); } // se filtra por area que procesa /*if (filtro.getIdAreaProcesa()!=null){ crit.createAlias("orden.codExamen", "examen"); crit.add( Restrictions.and( Restrictions.eq("examen.area.idArea", Integer.valueOf(filtro.getIdAreaProcesa()))) ); }*/ // Se filtra por rango de fecha de recepcion en laboratorio if (filtro.getFechaInicioRecepLab() != null && filtro.getFechaFinRecepLab() != null) { crit.add( Subqueries.propertyIn( "recepcion.idRecepcion", DetachedCriteria.forClass(RecepcionMxLab.class) .createAlias("recepcionMx", "recepcionGral") .add( Restrictions.between( "fechaHoraRecepcion", filtro.getFechaInicioRecepLab(), filtro.getFechaFinRecepLab())) .setProjection(Property.forName("recepcionGral.idRecepcion")))); } if (filtro.getIncluirMxInadecuada() != null && filtro.getIncluirMxInadecuada()) { crit.add( Restrictions.or(Restrictions.isNull("recepcion.calidadMx.codigo")) .add(Restrictions.or(Restrictions.ne("recepcion.calidadMx.codigo", "CALIDMX|IDC")))); } if (filtro.getCodigoUnicoMx() != null) { crit.add( Restrictions.or(Restrictions.eq("tomaMx.codigoUnicoMx", filtro.getCodigoUnicoMx())) .add( Restrictions.or(Restrictions.eq("tomaMx.codigoLab", filtro.getCodigoUnicoMx())))); } // se filtra por tipo de solicitud if (filtro.getCodTipoSolicitud() != null) { if (filtro.getCodTipoSolicitud().equals("Estudio")) { crit.add( Subqueries.propertyIn( "tomaMx.idTomaMx", DetachedCriteria.forClass(DaSolicitudEstudio.class) .createAlias("idTomaMx", "toma") .setProjection(Property.forName("toma.idTomaMx")))); } else { crit.add( Subqueries.propertyIn( "tomaMx.idTomaMx", DetachedCriteria.forClass(DaSolicitudDx.class) .createAlias("idTomaMx", "toma") .add( Subqueries.propertyIn( "labProcesa.codigo", DetachedCriteria.forClass(AutoridadLaboratorio.class) .createAlias("laboratorio", "labautorizado") .createAlias("user", "usuario") .add( Restrictions.eq( "pasivo", false)) // autoridad laboratorio activa .add( Restrictions.and( Restrictions.eq( "usuario.username", filtro.getNombreUsuario()))) // usuario .setProjection(Property.forName("labautorizado.codigo")))) .setProjection(Property.forName("toma.idTomaMx")))); } } // nombre solicitud if (filtro.getNombreSolicitud() != null) { if (filtro.getCodTipoSolicitud() != null) { if (filtro.getCodTipoSolicitud().equals("Estudio")) { crit.add( Subqueries.propertyIn( "solicitudtomaMx.idTomaMx", DetachedCriteria.forClass(DaSolicitudEstudio.class) .createAlias("tipoEstudio", "estudio") .add( Restrictions.ilike( "estudio.nombre", "%" + filtro.getNombreSolicitud() + "%")) .createAlias("idTomaMx", "toma") .setProjection(Property.forName("toma.idTomaMx")))); } else { crit.add( Subqueries.propertyIn( "tomaMx.idTomaMx", DetachedCriteria.forClass(DaSolicitudDx.class) .createAlias("codDx", "dx") .add(Restrictions.ilike("dx.nombre", "%" + filtro.getNombreSolicitud() + "%")) .createAlias("idTomaMx", "toma") .setProjection(Property.forName("toma.idTomaMx")))); } } else { Junction conditGroup = Restrictions.disjunction(); conditGroup .add( Subqueries.propertyIn( "tomaMx.idTomaMx", DetachedCriteria.forClass(DaSolicitudEstudio.class) .createAlias("tipoEstudio", "estudio") .add( Restrictions.ilike( "estudio.nombre", "%" + filtro.getNombreSolicitud() + "%")) .createAlias("idTomaMx", "toma") .setProjection(Property.forName("toma.idTomaMx")))) .add( Subqueries.propertyIn( "tomaMx.idTomaMx", DetachedCriteria.forClass(DaSolicitudDx.class) .createAlias("codDx", "dx") .add( Restrictions.ilike( "dx.nombre", "%" + filtro.getNombreSolicitud() + "%")) .createAlias("idTomaMx", "toma") .setProjection(Property.forName("toma.idTomaMx")))); crit.add(conditGroup); } } // se filtra que usuario tenga autorizado laboratorio al que se envio la muestra desde ALERTA /*if (filtro.getNombreUsuario()!=null) { crit.createAlias("tomaMx.envio","envioMx"); crit.add(Subqueries.propertyIn("envioMx.laboratorioDestino.codigo", DetachedCriteria.forClass(AutoridadLaboratorio.class) .createAlias("laboratorio", "labautorizado") .createAlias("user", "usuario") .add(Restrictions.eq("pasivo",false)) //autoridad laboratorio activa .add(Restrictions.and(Restrictions.eq("usuario.username",filtro.getNombreUsuario()))) //usuario .setProjection(Property.forName("labautorizado.codigo")))); }*/ if (filtro.getCodEstado() != null) { if (filtro .getCodEstado() .equalsIgnoreCase("ESTDMX|EPLAB")) { // significa que es recepción en laboratorio // Se filtra que el área a la que pertenece la solicitud este asociada al usuario // autenticado Junction conditGroup = Restrictions.disjunction(); conditGroup .add( Subqueries.propertyIn( "tomaMx.idTomaMx", DetachedCriteria.forClass(DaSolicitudEstudio.class) .createAlias("tipoEstudio", "estudio") .createAlias("estudio.area", "area") .add( Subqueries.propertyIn( "area.idArea", DetachedCriteria.forClass(AutoridadArea.class) .add(Restrictions.eq("pasivo", false)) // autoridad area activa .add( Restrictions.and( Restrictions.eq( "user.username", filtro.getNombreUsuario()))) // usuario .setProjection(Property.forName("area.idArea")))) .createAlias("idTomaMx", "toma") .setProjection(Property.forName("idTomaMx.idTomaMx")))) .add( Subqueries.propertyIn( "tomaMx.idTomaMx", DetachedCriteria.forClass(DaSolicitudDx.class) .createAlias("codDx", "dx") .createAlias("dx.area", "area") .add( Subqueries.propertyIn( "area.idArea", DetachedCriteria.forClass(AutoridadArea.class) .add(Restrictions.eq("pasivo", false)) // autoridad area activa .add( Restrictions.and( Restrictions.eq( "user.username", filtro.getNombreUsuario()))) // usuario .setProjection(Property.forName("area.idArea")))) .createAlias("idTomaMx", "toma") .setProjection(Property.forName("toma.idTomaMx")))); crit.add(conditGroup); } } // filtro que las rutinas pertenezcan al laboratorio del usuario que consulta crit.createAlias("recepcion.labRecepcion", "labRecep"); crit.add( Subqueries.propertyIn( "labRecep.codigo", DetachedCriteria.forClass(AutoridadLaboratorio.class) .createAlias("laboratorio", "labautorizado") .createAlias("user", "usuario") .add(Restrictions.eq("pasivo", false)) // autoridad laboratorio activa .add( Restrictions.and( Restrictions.eq("usuario.username", filtro.getNombreUsuario()))) // usuario .setProjection(Property.forName("labautorizado.codigo")))); // sólo la última recepción de cada muestra DetachedCriteria maxDateQuery = DetachedCriteria.forClass(RecepcionMx.class); maxDateQuery.createAlias("tomaMx", "mx"); maxDateQuery.add(Restrictions.eqProperty("mx.idTomaMx", "tomaMx.idTomaMx")); maxDateQuery.setProjection(Projections.max("fechaHoraRecepcion")); crit.add(Property.forName("fechaHoraRecepcion").eq(maxDateQuery)); // filtro sólo control calidad en el laboratio del usuario if (filtro.getControlCalidad() != null) { if (filtro .getControlCalidad()) { // si hay filtro por control de calidad y es "Si", sólo incluir // rutinas crit.add( Subqueries.propertyIn( "tomaMx.idTomaMx", DetachedCriteria.forClass(DaSolicitudDx.class) .add(Restrictions.eq("controlCalidad", filtro.getControlCalidad())) .createAlias("idTomaMx", "toma") .add( Subqueries.propertyIn( "labProcesa.codigo", DetachedCriteria.forClass(AutoridadLaboratorio.class) .createAlias("laboratorio", "labautorizado") .createAlias("user", "usuario") .add( Restrictions.eq( "pasivo", false)) // autoridad laboratorio activa .add( Restrictions.and( Restrictions.eq( "usuario.username", filtro.getNombreUsuario()))) // usuario .setProjection(Property.forName("labautorizado.codigo")))) .setProjection(Property.forName("toma.idTomaMx")))); } else { // si hay filtro por control de calidad y es "No", siempre incluir los estudios Junction conditGroup = Restrictions.disjunction(); conditGroup .add( Subqueries.propertyIn( "tomaMx.idTomaMx", DetachedCriteria.forClass(DaSolicitudDx.class) .add(Restrictions.eq("controlCalidad", filtro.getControlCalidad())) .createAlias("idTomaMx", "toma") .add( Subqueries.propertyIn( "labProcesa.codigo", DetachedCriteria.forClass(AutoridadLaboratorio.class) .createAlias("laboratorio", "labautorizado") .createAlias("user", "usuario") .add( Restrictions.eq( "pasivo", false)) // autoridad laboratorio activa .add( Restrictions.and( Restrictions.eq( "usuario.username", filtro.getNombreUsuario()))) // usuario .setProjection(Property.forName("labautorizado.codigo")))) .setProjection(Property.forName("toma.idTomaMx")))) .add( Restrictions.or( Subqueries.propertyIn( "tomaMx.idTomaMx", DetachedCriteria.forClass(DaSolicitudEstudio.class) .createAlias("idTomaMx", "idTomaMx") .setProjection(Property.forName("idTomaMx.idTomaMx"))))); crit.add(conditGroup); } } // filtro para sólo solicitudes aprobadas if (filtro.getSolicitudAprobada() != null) { Junction conditGroup = Restrictions.disjunction(); conditGroup .add( Subqueries.propertyIn( "tomaMx.idTomaMx", DetachedCriteria.forClass(DaSolicitudEstudio.class) .add(Restrictions.eq("aprobada", filtro.getSolicitudAprobada())) .createAlias("idTomaMx", "toma") .setProjection(Property.forName("toma.idTomaMx")))) .add( Subqueries.propertyIn( "tomaMx.idTomaMx", DetachedCriteria.forClass(DaSolicitudDx.class) .add(Restrictions.eq("aprobada", filtro.getSolicitudAprobada())) // .add(Restrictions.eq("controlCalidad",false)) ¿¿¿¿¿¿¿¿¿????????????? .createAlias("idTomaMx", "toma") .setProjection(Property.forName("toma.idTomaMx")))); crit.add(conditGroup); } return crit.list(); }
@Override public Iterator<Item> findByMetadataQuery( Context context, List<List<MetadataField>> listFieldList, List<String> query_op, List<String> query_val, List<UUID> collectionUuids, String regexClause, int offset, int limit) throws SQLException { Criteria criteria = createCriteria(context, Item.class, "item"); criteria.setFirstResult(offset); criteria.setMaxResults(limit); if (!collectionUuids.isEmpty()) { DetachedCriteria dcollCriteria = DetachedCriteria.forClass(Collection.class, "coll"); dcollCriteria.setProjection(Projections.property("coll.id")); dcollCriteria.add(Restrictions.eqProperty("coll.id", "item.owningCollection")); dcollCriteria.add(Restrictions.in("coll.id", collectionUuids)); criteria.add(Subqueries.exists(dcollCriteria)); } int index = Math.min(listFieldList.size(), Math.min(query_op.size(), query_val.size())); StringBuilder sb = new StringBuilder(); for (int i = 0; i < index; i++) { OP op = OP.valueOf(query_op.get(i)); if (op == null) { log.warn("Skipping Invalid Operator: " + query_op.get(i)); continue; } if (op == OP.matches || op == OP.doesnt_match) { if (regexClause.isEmpty()) { log.warn("Skipping Unsupported Regex Operator: " + query_op.get(i)); continue; } } DetachedCriteria subcriteria = DetachedCriteria.forClass(MetadataValue.class, "mv"); subcriteria.add(Property.forName("mv.dSpaceObject").eqProperty("item.id")); subcriteria.setProjection(Projections.property("mv.dSpaceObject")); if (!listFieldList.get(i).isEmpty()) { subcriteria.add(Restrictions.in("metadataField", listFieldList.get(i))); } sb.append(op.name() + " "); if (op == OP.equals || op == OP.not_equals) { subcriteria.add(Property.forName("mv.value").eq(query_val.get(i))); sb.append(query_val.get(i)); } else if (op == OP.like || op == OP.not_like) { subcriteria.add(Property.forName("mv.value").like(query_val.get(i))); sb.append(query_val.get(i)); } else if (op == OP.contains || op == OP.doesnt_contain) { subcriteria.add(Property.forName("mv.value").like("%" + query_val.get(i) + "%")); sb.append(query_val.get(i)); } else if (op == OP.matches || op == OP.doesnt_match) { subcriteria.add( Restrictions.sqlRestriction(regexClause, query_val.get(i), StandardBasicTypes.STRING)); sb.append(query_val.get(i)); } if (op == OP.exists || op == OP.equals || op == OP.like || op == OP.contains || op == OP.matches) { criteria.add(Subqueries.exists(subcriteria)); } else { criteria.add(Subqueries.notExists(subcriteria)); } } log.debug(String.format("Running custom query with %d filters", index)); return list(criteria).iterator(); }
public List<DmFolder> getSharedFirstLevelList(String accountSharedId, String accountOwnerId) { DmAccount permittedAccount = null; if (accountSharedId != null) { permittedAccount = new DmAccount(); permittedAccount.setId(accountSharedId); } DmAccount ownerAccount = null; if (accountOwnerId != null) { ownerAccount = new DmAccount(); ownerAccount.setId(accountOwnerId); } List<DmFolder> folderList = null; if (permittedAccount != null) { Criteria crit = getSession().createCriteria(DmFolderPermission.class); crit.setProjection(Projections.property("folder")); Conjunction conjunction = Restrictions.conjunction(); // conjunction.add(Restrictions.ge("permissionType", // ApplicationConstants.FOLDER_PERMISSION_MANAGER)); conjunction.add(Restrictions.eq("account", permittedAccount)); conjunction.add(Restrictions.ne("account", ownerAccount)); crit.add(conjunction); crit.createAlias("folder", "folderShared", CriteriaSpecification.LEFT_JOIN); crit.add(Restrictions.eq("folderShared.owner", ownerAccount)); crit.createAlias("folderShared.parent", "parentFolder", CriteriaSpecification.LEFT_JOIN); // crit.createAlias("parentFolder.permissionList", "parentPermission"); crit.createAlias( "parentFolder.permissionList", "parentPermission", CriteriaSpecification.LEFT_JOIN); // DetachedCriteria subquery = DetachedCriteria.forClass(DmFolder.class, // "last_pos"); DetachedCriteria subquery = DetachedCriteria.forClass(DmFolderPermission.class); subquery.setProjection(Projections.property("folder")); subquery.add(conjunction); Disjunction disjunction = Restrictions.disjunction(); disjunction.add(Restrictions.isNull("folderShared.parent")); // disjunction.add(Restrictions.isNull("parentFolder.permissionList")); // disjunction.add(Restrictions.isNull("parentPermission.id")); // disjunction.add(conjunction2); disjunction.add(Subqueries.propertyNotIn("folderShared.parent", subquery)); // crit.add(Subqueries.propertyNotIn("folderShared.parent", subquery)); // Conjunction conjunction2 = Restrictions.conjunction(); // conjunction2.add(Restrictions.eq("parentPermission.permissionType", // ApplicationConstants.FOLDER_PERMISSION_MANAGER)); // conjunction2.add(Restrictions.eq("parentPermission.account", permittedAccount)); // // Conjunction conjunction3 = Restrictions.conjunction(); // conjunction3.add(Restrictions.eq("parentPermission.permissionType", // ApplicationConstants.FOLDER_PERMISSION_MANAGER)); // conjunction3.add(Restrictions.eq("parentPermission.account", permittedAccount)); // disjunction.add(conjunction3); // disjunction.add(Restrictions.ne("parentPermission.account", permittedAccount)); // disjunction.add(Restrictions.eq("parentPermission.permissionType", // ApplicationConstants.FOLDER_PERMISSION_MANAGER)); // disjunction.add(Restrictions.isNull("parentFolder.permissionList")); // disjunction.add(Restrictions.eq("parentPermission.permissionType", // ApplicationConstants.FOLDER_PERMISSION_MANAGER)); // disjunction.add(Restrictions.ne("parentPermission.account", permittedAccount)); crit.add(disjunction); folderList = crit.list(); // start - get children for each child (trigger lazy fetch) for (DmFolder folderTmp : folderList) { if (folderTmp.getChildList() != null) { folderTmp.getChildList().size(); } } // end - get children for each child (trigger lazy fetch) } return folderList; }
private Criterion parseExpression(Expression expression) { ExpressionTypes type = expression.getType(); String propertyName = expression.getTargetPropertyName(); Object value = expression.getValue(); Class<?> clazz; if (log.isTraceEnabled()) { log.trace( String.format( "Parsing expression of type '%s' for propety '%s', value=%s", type.name(), propertyName, value)); } switch (type) { case EQUAL: return org.hibernate.criterion.Restrictions.eq(propertyName, value); case GREATER: return org.hibernate.criterion.Restrictions.gt(propertyName, value); case GREATER_OR_EQUAL: return org.hibernate.criterion.Restrictions.ge(propertyName, value); case LESS: return org.hibernate.criterion.Restrictions.lt(propertyName, value); case LESS_OR_EQUAL: return org.hibernate.criterion.Restrictions.le(propertyName, value); case LIKE: String sval = (String) value; if (sval.contains("%") || sval.contains("_")) { return org.hibernate.criterion.Restrictions.ilike(propertyName, sval); } else { return org.hibernate.criterion.Restrictions.ilike(propertyName, sval, MatchMode.ANYWHERE); } case LIKE_END: return org.hibernate.criterion.Restrictions.ilike( propertyName, (String) value, MatchMode.END); case LIKE_START: return org.hibernate.criterion.Restrictions.ilike( propertyName, (String) value, MatchMode.START); case LIKE_EXACT: return org.hibernate.criterion.Restrictions.ilike( propertyName, (String) value, MatchMode.EXACT); case BETWEEN: return org.hibernate.criterion.Restrictions.between( propertyName, ((Object[]) value)[0], ((Object[]) value)[1]); case IN: clazz = value.getClass(); if (clazz.isArray()) { return org.hibernate.criterion.Restrictions.in(propertyName, (Object[]) value); } else if (Collection.class.isAssignableFrom(clazz)) { return org.hibernate.criterion.Restrictions.in(propertyName, (Collection<?>) value); } else { throw new IllegalStateException( "Object for 'IN' criteria must be array or collection, but it is " + (clazz == null ? "(null)" : "'" + clazz.getName() + "'")); } case IS_NULL: return org.hibernate.criterion.Restrictions.isNull(propertyName); case IS_NOT_NULL: return org.hibernate.criterion.Restrictions.isNotNull(propertyName); case NOT_EQUAL: return org.hibernate.criterion.Restrictions.ne(propertyName, value); case EXISTS: return Subqueries.exists(subquery((SubqueryExpression) expression)); case NOT_EXISTS: return Subqueries.notExists(subquery((SubqueryExpression) expression)); case EQUAL_PROPERTY: if (!(value instanceof CharSequence)) { throw new IllegalStateException( "Value for 'EQUAL_PROPERTY' criteria must be CharSequence, but it is " + (value == null ? "(null)" : "'" + value.getClass().getName() + "'")); } return org.hibernate.criterion.Restrictions.eqProperty(propertyName, value.toString()); case GREATER_PROPERTY: return org.hibernate.criterion.Restrictions.gtProperty(propertyName, value.toString()); case LESS_PROPERTY: return org.hibernate.criterion.Restrictions.ltProperty(propertyName, value.toString()); case GREATER_EQUAL_PROPERTY: return org.hibernate.criterion.Restrictions.geProperty(propertyName, value.toString()); case LESS_EQUAL_PROPERTY: return org.hibernate.criterion.Restrictions.leProperty(propertyName, value.toString()); case SQL_RESTICTION: return org.hibernate.criterion.Restrictions.sqlRestriction(value.toString()); default: throw new IllegalStateException( String.format("Unknown query expression '%s'", type.name())); } }