List of usage examples for org.hibernate.criterion Restrictions conjunction
public static Conjunction conjunction()
From source file:org.openmrs.api.db.hibernate.PersonSearchCriteria.java
License:Mozilla Public License
Criterion prepareCriterionForName(String value, Boolean voided) { if (voided == null || !voided) { return Restrictions.conjunction().add(Restrictions.eq("name.voided", false)) .add(Restrictions.disjunction() .add(Restrictions.ilike("name.givenName", value, MatchMode.START)) .add(Restrictions.ilike("name.middleName", value, MatchMode.START)) .add(Restrictions.ilike("name.familyName", value, MatchMode.START)) .add(Restrictions.ilike("name.familyName2", value, MatchMode.START))); } else {/*from ww w .j a va 2 s .c o m*/ return Restrictions.conjunction() .add(Restrictions.disjunction() .add(Restrictions.ilike("name.givenName", value, MatchMode.START)) .add(Restrictions.ilike("name.middleName", value, MatchMode.START)) .add(Restrictions.ilike("name.familyName", value, MatchMode.START)) .add(Restrictions.ilike("name.familyName2", value, MatchMode.START))); } }
From source file:org.openmrs.module.appointmentscheduling.api.db.hibernate.HibernateAppointmentBlockDAO.java
License:Open Source License
/** * Returns the overlapping appointment blocks to the given appointment block. * /*w w w. ja va 2s . c om*/ * @param appointmentBlock is the appointment block for which we want to test overlap. * @return the appointment blocks that overlaps to the given appointment block. */ @SuppressWarnings("unchecked") @Override @Transactional(readOnly = true) public List<AppointmentBlock> getOverlappingAppointmentBlocks(AppointmentBlock appointmentBlock) { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(AppointmentBlock.class); Disjunction disjunction = Restrictions.disjunction(); if (appointmentBlock != null) { Date fromDate = appointmentBlock.getStartDate(); Date toDate = appointmentBlock.getEndDate(); if (fromDate != null && toDate != null) { //let givenAppointmentBlock.startDate = fromDate, givenAppointmentBlock.endDate = toDate. //let checkedAppointmentBlock.startDate = fromDate' , checkedAppointmentBlock.endDate = toDate'. //1) create the conjunction - (fromDate>=fromDate' AND fromDate<toDate') Conjunction conjunction = Restrictions.conjunction(); conjunction.add(Restrictions.le("startDate", fromDate)); conjunction.add(Restrictions.gt("endDate", fromDate)); //add the conjunction to the disjunction disjunction.add(conjunction); //2) create the conjunction - (fromDate<fromDate' AND toDate>fromDate') conjunction = Restrictions.conjunction(); conjunction.add(Restrictions.gt("startDate", fromDate)); conjunction.add(Restrictions.lt("startDate", toDate)); //add the conjunction to the disjunction disjunction.add(conjunction); //the disjunction - (fromDate>=fromDate' AND fromDate<toDate') OR (fromDate<fromDate' AND toDate>fromDate') criteria.add(disjunction); //restriction for the provider criteria.add(Restrictions.eq("provider", appointmentBlock.getProvider())); if (appointmentBlock.getAppointmentBlockId() != null) { //restriction for not comparing the same appointment blocks criteria.add(Restrictions.ne("appointmentBlockId", appointmentBlock.getAppointmentBlockId())); } //restriction for ignoring "voided" appointment blocks criteria.add(Restrictions.eq("voided", false)); return criteria.list(); } } return new ArrayList<AppointmentBlock>(); }
From source file:org.openmrs.module.cohort.api.db.hibernate.HibernateCohortDAO.java
License:Open Source License
private Criteria createEncounterByQueryCriteria(String query, Integer cohortId, boolean includeVoided, boolean orderByNames) { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(CohortEncounter.class, "enc"); if (!includeVoided) { criteria.add(Restrictions.eq("enc.voided", false)); }// w ww . ja va 2s.c o m criteria = criteria.createCriteria("cohort", "coh"); if (cohortId != null) { criteria.add(Restrictions.eq("coh.cohortId", cohortId)); if (StringUtils.isNotBlank(query)) { criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); //match on location.name, encounterType.name, form.name //provider.name, provider.identifier, provider.person.names MatchMode mode = MatchMode.ANYWHERE; criteria.createAlias("enc.location", "loc"); criteria.createAlias("enc.encounterType", "encType"); criteria.createAlias("enc.form", "form"); criteria.createAlias("enc.encounterProviders", "enc_prov"); criteria.createAlias("enc_prov.provider", "prov"); criteria.createAlias("prov.person", "person", Criteria.LEFT_JOIN); criteria.createAlias("person.names", "personName", Criteria.LEFT_JOIN); Disjunction or = Restrictions.disjunction(); or.add(Restrictions.ilike("loc.name", query, mode)); or.add(Restrictions.ilike("encType.name", query, mode)); or.add(Restrictions.ilike("form.name", query, mode)); or.add(Restrictions.ilike("prov.name", query, mode)); or.add(Restrictions.ilike("prov.identifier", query, mode)); String[] splitNames = query.split(" "); Disjunction nameOr = Restrictions.disjunction(); for (String splitName : splitNames) { nameOr.add(Restrictions.ilike("personName.givenName", splitName, mode)); nameOr.add(Restrictions.ilike("personName.middleName", splitName, mode)); nameOr.add(Restrictions.ilike("personName.familyName", splitName, mode)); nameOr.add(Restrictions.ilike("personName.familyName2", splitName, mode)); } //OUTPUT for provider criteria: //prov.name like '%query%' OR prov.identifier like '%query%' //OR ( personName.voided = false // AND ( personName.givenName like '%query%' // OR personName.middleName like '%query%' // OR personName.familyName like '%query%' // OR personName.familyName2 like '%query%' // ) // ) Conjunction personNameConjuction = Restrictions.conjunction(); personNameConjuction.add(Restrictions.eq("personName.voided", false)); personNameConjuction.add(nameOr); or.add(personNameConjuction); criteria.add(or); } } else { String name = null; String identifier = null; if (query.matches(".*\\d+.*")) { identifier = query; } else { // there is no number in the string, search on name name = query; } criteria = new PatientSearchCriteria(sessionFactory, criteria).prepareCriteria(name, identifier, new ArrayList<PatientIdentifierType>(), false, orderByNames, false); } return criteria; }
From source file:org.openmrs.module.errorlogging.api.db.hibernate.HibernateExceptionLogDAO.java
License:Open Source License
/** * Utility method that returns a criteria for searching for exception logs * that match the specified search phrase and arguments * * @param username user who experienced the exception * @param exceptionClass class name of the exception * @param exceptionMessage message on the exception * @param openmrsVersion version of the OpenMRS * @param fileName file name where the exception occurred * @param lineNum line number of the file where the exception occurred * @param startExceptionDateTime date since which exceptions thrown * @param endExceptionDateTime date to which exceptions thrown * @param start starting from the "start" record * @param length retrieve the next "length" records from database * @return the generated criteria object *//* w ww .ja v a 2 s . c o m*/ private Criteria createExceptionLogSearchCriteria(String username, String exceptionClass, String exceptionMessage, String openmrsVersion, String fileName, String methodName, Integer lineNum, Date startExceptionDateTime, Date endExceptionDateTime) { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(ExceptionLog.class); Conjunction junction = Restrictions.conjunction(); if (username != null) { DetachedCriteria subCriteria = DetachedCriteria.forClass(User.class); subCriteria.add(Restrictions.like("username", username)); subCriteria.setProjection(Projections.property("userId")); junction.add(Subqueries.propertyEq("creator.userId", subCriteria)); } if (exceptionClass != null) { criteria.add(Restrictions.like("exceptionClass", exceptionClass)); } if (exceptionMessage != null) { criteria.add(Restrictions.like("exceptionMessage", exceptionMessage, MatchMode.ANYWHERE)); } if (openmrsVersion != null) { criteria.add(Restrictions.like("openmrsVersion", openmrsVersion)); } if (fileName != null) { DetachedCriteria subCriteria = DetachedCriteria.forClass(ExceptionLogDetail.class); subCriteria.add(Restrictions.like("fileName", fileName)); subCriteria.setProjection(Projections.property("exceptionLogDetailId")); junction.add(Subqueries.propertyIn("exceptionLogId", subCriteria)); } if (methodName != null) { DetachedCriteria subCriteria = DetachedCriteria.forClass(ExceptionLogDetail.class); subCriteria.add(Restrictions.like("methodName", methodName)); subCriteria.setProjection(Projections.property("exceptionLogDetailId")); junction.add(Subqueries.propertyIn("exceptionLogId", subCriteria)); } if (lineNum != null) { DetachedCriteria subCriteria = DetachedCriteria.forClass(ExceptionLogDetail.class); subCriteria.add(Restrictions.eq("lineNumber", lineNum)); subCriteria.setProjection(Projections.property("exceptionLogDetailId")); junction.add(Subqueries.propertyIn("exceptionLogId", subCriteria)); } if (startExceptionDateTime != null) { criteria.add(Restrictions.ge("dateCreated", startExceptionDateTime)); } if (endExceptionDateTime != null) { criteria.add(Restrictions.le("dateCreated", endExceptionDateTime)); } criteria.add(junction); return criteria; }
From source file:org.openmrs.module.patientaccesscontrol.api.db.hibernate.HibernatePatientAccessControlDAO.java
License:Open Source License
private Criteria createPatientCriteria(Collection<Integer> includePatients, Collection<Integer> excludePatients, Collection<Program> includePrograms, boolean includeProgramAlias, boolean orderByProgram) { Date now = new Date(); Criteria criteria = sessionFactory.getCurrentSession().createCriteria(ModulePatient.class, "patient"); if (includeProgramAlias) { criteria.createAlias("patientPrograms", "pp", Criteria.LEFT_JOIN, Restrictions.conjunction().add(Restrictions.eq("pp.voided", false)) .add(Restrictions.or(Restrictions.isNull("pp.dateEnrolled"), Restrictions.le("pp.dateEnrolled", now))) .add(Restrictions.or(Restrictions.isNull("pp.dateCompleted"), Restrictions.ge("pp.dateCompleted", now)))) .createAlias("pp.program", "program", Criteria.LEFT_JOIN); if (orderByProgram) { criteria.addOrder(OrderNullsLast.asc("program.name")); }//from w ww.j av a2 s . c o m if (includePrograms != null) { if (includePrograms.isEmpty()) { criteria.add(Restrictions.isNull("pp.program")); } else { criteria.add(Restrictions.or(Restrictions.isNull("pp.program"), Restrictions.in("pp.program", includePrograms))); } } } if (includePatients != null) { criteria.add(Restrictions.in("patientId", includePatients)); } if (excludePatients != null && !excludePatients.isEmpty()) { criteria.add(Restrictions.not(Restrictions.in("patientId", excludePatients))); } return criteria; }
From source file:org.openmrs.module.patientaccesscontrol.api.db.hibernate.HibernateRoleProgramDAO.java
License:Open Source License
private Criteria createPatientCriteria(List<Program> includePrograms) { Date now = new Date(); Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Patient.class, "patient").createAlias( "patientPrograms", "pp", Criteria.INNER_JOIN, Restrictions.conjunction().add(Restrictions.eq("pp.voided", false)) .add(Restrictions.or(Restrictions.isNull("pp.dateEnrolled"), Restrictions.le("pp.dateEnrolled", now))) .add(Restrictions.or(Restrictions.isNull("pp.dateCompleted"), Restrictions.ge("pp.dateCompleted", now)))); criteria.add(Restrictions.in("pp.program", includePrograms)); return criteria; }
From source file:org.openmrs.module.registrationcore.api.search.BasicSimilarPatientSearchAlgorithm.java
License:Open Source License
/** * @should find by exact country and exact city * @should find by exact gender// w ww. ja v a 2 s. c om * @should find by partial given and partial family name * @should find by birthday within two weeks */ @Override @Transactional(readOnly = true) public List<PatientAndMatchQuality> findSimilarPatients(Patient patient, Map<String, Object> otherDataPoints, Double cutoff, Integer maxResults) { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Patient.class); criteria.add(Restrictions.eq("voided", false)); if (!StringUtils.isBlank(patient.getGender())) { criteria.add(Restrictions.eq("gender", patient.getGender())); } if (patient.getBirthdate() != null) { Date birthdate = patient.getBirthdate(); addDateWithinPeriodRestriction(criteria, birthdate, birthdateRangePeriod); } if (patient.getNames() != null && !patient.getNames().isEmpty()) { criteria.createAlias("names", "names"); for (PersonName name : patient.getNames()) { criteria.add(Restrictions.eq("names.voided", false)); Disjunction or = Restrictions.disjunction(); addLikeIfNotBlankRestriction(or, "names.givenName", name.getGivenName(), MatchMode.START); addLikeIfNotBlankRestriction(or, "names.middleName", name.getMiddleName(), MatchMode.START); addLikeIfNotBlankRestriction(or, "names.familyName", name.getFamilyName(), MatchMode.START); criteria.add(or); } } if (patient.getAddresses() != null && !patient.getAddresses().isEmpty()) { criteria.createAlias("addresses", "addresses"); for (PersonAddress address : patient.getAddresses()) { criteria.add(Restrictions.eq("addresses.voided", false)); Conjunction and = Restrictions.conjunction(); addLikeIfNotBlankRestriction(and, "addresses.country", address.getCountry(), MatchMode.EXACT); addLikeIfNotBlankRestriction(and, "addresses.cityVillage", address.getCityVillage(), MatchMode.EXACT); criteria.add(and); } } @SuppressWarnings("unchecked") List<Patient> patients = criteria.list(); List<PatientAndMatchQuality> matches = new ArrayList<PatientAndMatchQuality>(); for (Patient match : patients) { List<String> matchedFields = new ArrayList<String>(); double score = 0; if (patient.getBirthdate() != null && match.getBirthdate() != null) { long birthdateDistance = Math .abs(patient.getBirthdate().getTime() - match.getBirthdate().getTime()); if (birthdateDistance < birthdateRangePeriod) { matchedFields.add("birthdate"); } double birthdateScore = 1.0 / Math.log((1.0 + birthdateDistance)); score += birthdateScore; } for (PersonName patientName : patient.getNames()) { for (PersonName matchName : match.getNames()) { double familyNameScore = countStartWithScoreForField(matchName.getFamilyName(), patientName.getFamilyName()); if (familyNameScore != 0) { score += familyNameScore; matchedFields.add("names.familyName"); } double givenNameScore = countStartWithScoreForField(matchName.getGivenName(), patientName.getGivenName()); if (givenNameScore != 0) { matchedFields.add("names.givenName"); score += givenNameScore; } double middleNameScore = countStartWithScoreForField(matchName.getMiddleName(), patientName.getMiddleName()); if (middleNameScore != 0) { matchedFields.add("names.middleName"); score += middleNameScore; } } } for (PersonAddress patientAddress : patient.getAddresses()) { for (PersonAddress matchAddress : match.getAddresses()) { if (!StringUtils.isBlank(matchAddress.getCountry()) && matchAddress.getCountry().equals(patientAddress.getCountry())) { matchedFields.add("addresses.country"); score += 1; } if (!StringUtils.isBlank(matchAddress.getCityVillage()) && matchAddress.getCityVillage().equals(patientAddress.getCityVillage())) { matchedFields.add("addresses.cityVillage"); score += 1; } } } if (cutoff == null) { matches.add(new PatientAndMatchQuality(match, score, matchedFields)); } else { if (score >= cutoff) { matches.add(new PatientAndMatchQuality(match, score, matchedFields)); } } } Collections.sort(matches); if (maxResults != null && matches.size() > maxResults) { return matches.subList(0, maxResults); } else { return matches; } }
From source file:org.opennms.web.filter.AndFilter.java
License:Open Source License
/** {@inheritDoc} */ @Override/*from w ww . j av a 2s. com*/ public Criterion getCriterion() { Conjunction conjunction = Restrictions.conjunction(); for (Filter filter : getFilters()) { conjunction.add(filter.getCriterion()); } return conjunction; }
From source file:org.sculptor.framework.accessimpl.jpahibernate.JpaHibFindByConditionAccessImpl.java
License:Apache License
private Criterion makeCriterion(ConditionalCriteria crit) { if (crit == null) { return null; }/*w ww .j av a 2 s . c o m*/ ConditionalCriteria.Operator operator = crit.getOperator(); if (Operator.Equal.equals(operator)) { return Restrictions.eq(makePathWithAlias(crit.getPropertyFullName()), crit.getFirstOperant()); } else if (Operator.IgnoreCaseEqual.equals(operator)) { return Restrictions.eq(makePathWithAlias(crit.getPropertyFullName()), crit.getFirstOperant()) .ignoreCase(); } else if (Operator.LessThan.equals(operator)) { return Restrictions.lt(makePathWithAlias(crit.getPropertyFullName()), crit.getFirstOperant()); } else if (Operator.LessThanOrEqual.equals(operator)) { return Restrictions.le(makePathWithAlias(crit.getPropertyFullName()), crit.getFirstOperant()); } else if (Operator.GreatThan.equals(operator)) { return Restrictions.gt(makePathWithAlias(crit.getPropertyFullName()), crit.getFirstOperant()); } else if (Operator.GreatThanOrEqual.equals(operator)) { return Restrictions.ge(makePathWithAlias(crit.getPropertyFullName()), crit.getFirstOperant()); } else if (Operator.Like.equals(operator)) { // Hibernate bug HHH-5339 + PostgreSQL missing 'number like string' conversion return new NumericLikeExpression(makePathWithAlias(crit.getPropertyFullName()), crit.getFirstOperant().toString(), false); } else if (Operator.IgnoreCaseLike.equals(operator)) { // Hibernate bug HHH-5339 + PostgreSQL missing 'number like string' conversion return new NumericLikeExpression(makePathWithAlias(crit.getPropertyFullName()), crit.getFirstOperant().toString(), true); } else if (Operator.IsNull.equals(operator)) { return Restrictions.isNull(makePathWithAlias(crit.getPropertyFullName())); } else if (Operator.IsNotNull.equals(operator)) { return Restrictions.isNotNull(makePathWithAlias(crit.getPropertyFullName())); } else if (Operator.IsEmpty.equals(operator)) { return Restrictions.isEmpty(makePathWithAlias(crit.getPropertyFullName())); } else if (Operator.IsNotEmpty.equals(operator)) { return Restrictions.isNotEmpty(makePathWithAlias(crit.getPropertyFullName())); } else if (Operator.Not.equals(operator)) { return Restrictions.not(makeCriterion((ConditionalCriteria) crit.getFirstOperant())); } else if (Operator.Or.equals(operator) && crit.getFirstOperant() instanceof List<?>) { Disjunction disj = Restrictions.disjunction(); List<?> disjList = (List<?>) crit.getFirstOperant(); for (Object disjPart : disjList) { disj.add(makeCriterion((ConditionalCriteria) disjPart)); } return disj; } else if (Operator.Or.equals(operator)) { return Restrictions.or(makeCriterion((ConditionalCriteria) crit.getFirstOperant()), makeCriterion((ConditionalCriteria) crit.getSecondOperant())); } else if (Operator.And.equals(operator) && crit.getFirstOperant() instanceof List<?>) { Conjunction conj = Restrictions.conjunction(); List<?> conjList = (List<?>) crit.getFirstOperant(); for (Object conjPart : conjList) { conj.add(makeCriterion((ConditionalCriteria) conjPart)); } return conj; } else if (Operator.And.equals(operator)) { return Restrictions.and(makeCriterion((ConditionalCriteria) crit.getFirstOperant()), makeCriterion((ConditionalCriteria) crit.getSecondOperant())); } else if (Operator.In.equals(operator)) { if (crit.getFirstOperant() instanceof Collection<?>) { return Restrictions.in(makePathWithAlias(crit.getPropertyFullName()), (Collection<?>) crit.getFirstOperant()); } else { return Restrictions.in(makePathWithAlias(crit.getPropertyFullName()), (Object[]) crit.getFirstOperant()); } } else if (Operator.Between.equals(operator)) { return Restrictions.between(makePathWithAlias(crit.getPropertyFullName()), crit.getFirstOperant(), crit.getSecondOperant()); } else if (Operator.DistinctRoot.equals(operator)) { realDistinctRoot = true; return null; } else if (Operator.ProjectionRoot.equals(operator)) { resultTransformer = Criteria.PROJECTION; return null; } else if (Operator.EqualProperty.equals(operator)) { return Restrictions.eqProperty(makePathWithAlias(crit.getPropertyFullName()), (String) crit.getFirstOperant()); } else if (Operator.LessThanProperty.equals(operator)) { return Restrictions.ltProperty(makePathWithAlias(crit.getPropertyFullName()), (String) crit.getFirstOperant()); } else if (Operator.LessThanOrEqualProperty.equals(operator)) { return Restrictions.leProperty(makePathWithAlias(crit.getPropertyFullName()), (String) crit.getFirstOperant()); } else if (Operator.GreatThanProperty.equals(operator)) { return Restrictions.gtProperty(makePathWithAlias(crit.getPropertyFullName()), (String) crit.getFirstOperant()); } else if (Operator.GreatThanOrEqualProperty.equals(operator)) { return Restrictions.geProperty(makePathWithAlias(crit.getPropertyFullName()), (String) crit.getFirstOperant()); } else { return null; } }
From source file:org.sigmah.server.dao.hibernate.FilterCriterionBridge.java
License:Open Source License
/** * Given a filter, creates the Hibernate criteria need to call * {@link HibernateSiteTableDAO}// ww w. jav a 2s . c om * * @param filter * @return */ public static Criterion resolveCriterion(Filter filter) { Conjunction criterion = Restrictions.conjunction(); addRestriction(criterion, filter, DimensionType.Database, SiteTableColumn.database_id); addRestriction(criterion, filter, DimensionType.Activity, SiteTableColumn.activity_id); addRestriction(criterion, filter, DimensionType.Partner, SiteTableColumn.partner_id); addRestriction(criterion, filter, DimensionType.Site, SiteTableColumn.id); addAdminRestriction(criterion, filter); if (filter.isDateRestricted()) { if (filter.getMinDate() != null && filter.getMaxDate() == null) { criterion.add(Restrictions.disjunction() .add(Restrictions.ge(SiteTableColumn.date1.property(), filter.getMinDate())) .add(Restrictions.ge(SiteTableColumn.date2.property(), filter.getMinDate()))); } else if (filter.getMaxDate() != null && filter.getMinDate() == null) { criterion.add(Restrictions.disjunction() .add(Restrictions.le(SiteTableColumn.date1.property(), filter.getMaxDate())) .add(Restrictions.le(SiteTableColumn.date2.property(), filter.getMaxDate()))); } else { criterion.add(Restrictions.disjunction() .add(Restrictions.between(SiteTableColumn.date1.property(), filter.getMinDate(), filter.getMaxDate())) .add(Restrictions.between(SiteTableColumn.date2.property(), filter.getMinDate(), filter.getMaxDate()))); } } return criterion; }