List of usage examples for javax.persistence.criteria CriteriaBuilder like
Predicate like(Expression<String> x, String pattern);
From source file:org.openregistry.core.repository.jpa.JpaPersonRepository.java
public List<Person> searchByCriteria(final SearchCriteria searchCriteria) throws RepositoryAccessException { final String givenName = searchCriteria.getGivenName(); final String familyName = searchCriteria.getFamilyName(); final Date birthDate = searchCriteria.getDateOfBirth(); final String searchCriteriaName = searchCriteria.getName(); // search by role criteria final String sponsorNetID = searchCriteria.getSponsorNetID(); final OrganizationalUnit organizationalUnit = searchCriteria.getOrganizationalUnit(); final Date roleExpDate = searchCriteria.getRoleExpDate(); final Type roleType = searchCriteria.getAffiliationType(); final CriteriaBuilder criteriaBuilder = this.entityManager.getCriteriaBuilder(); final CriteriaQuery<JpaPersonImpl> c = criteriaBuilder.createQuery(JpaPersonImpl.class); c.distinct(true);/*from w ww . j a va 2s . c om*/ final Root<JpaPersonImpl> person = c.from(JpaPersonImpl.class); final Join<JpaPersonImpl, JpaNameImpl> name = person.join(JpaPersonImpl_.names); final Join<JpaPersonImpl, JpaRoleImpl> role = person.join(JpaPersonImpl_.roles); // person.fetch(JpaPersonImpl_.names); // person.fetch(JpaPersonImpl_.roles); // person.fetch(JpaPersonImpl_.identifiers); final Predicate pBirthDate; if (birthDate != null) { pBirthDate = criteriaBuilder.equal(person.get(JpaPersonImpl_.dateOfBirth), birthDate); } else { pBirthDate = null; } Predicate combined = null; if (StringUtils.hasText(givenName) && StringUtils.hasText(familyName)) { // final Predicate pGivenName = criteriaBuilder.equal(name.get(JpaNameImpl_.given), givenName ); Expression<String> pattern = criteriaBuilder.literal((String) givenName + "%"); final Predicate pGivenName = criteriaBuilder.like(name.get(JpaNameImpl_.given), pattern); final Predicate pFamilyName = criteriaBuilder.equal(name.get(JpaNameImpl_.family), familyName); combined = criteriaBuilder.and(pGivenName, pFamilyName); } else if (StringUtils.hasText(givenName)) { combined = criteriaBuilder.equal(name.get(JpaNameImpl_.given), givenName); } else if (StringUtils.hasText(familyName)) { combined = criteriaBuilder.equal(name.get(JpaNameImpl_.family), familyName); } else if (StringUtils.hasText(searchCriteriaName)) { final Predicate pGivenName = criteriaBuilder.equal(name.get(JpaNameImpl_.given), searchCriteriaName); final Predicate pFamilyName = criteriaBuilder.equal(name.get(JpaNameImpl_.family), searchCriteriaName); combined = criteriaBuilder.or(pGivenName, pFamilyName); } Predicate pRoleCombined = null; if (roleType != null) { //final Join<JpaPersonImpl,JpaRoleImpl> role = person.join(JpaPersonImpl_.roles); //final Join<JpaPersonImpl,JpaRoleImpl> role = name.join(JpaPersonImpl_.roles); pRoleCombined = criteriaBuilder.equal(role.get(JpaRoleImpl_.affiliationType), roleType); } if (organizationalUnit != null && StringUtils.hasText(organizationalUnit.getName())) { Predicate orgUnitP = criteriaBuilder.equal(role.get(JpaRoleImpl_.organizationalUnit), organizationalUnit); if (pRoleCombined != null) pRoleCombined = criteriaBuilder.and(pRoleCombined, orgUnitP); else pRoleCombined = orgUnitP; //pRoleCombined = criteriaBuilder.and(pRoleCombined, orgUnitP); } if (StringUtils.hasText(sponsorNetID)) { Person person1 = findByIdentifier(Type.IdentifierTypes.NETID.name(), sponsorNetID); if (person1 != null) { Predicate sponsorP = criteriaBuilder.equal(role.get(JpaRoleImpl_.sponsorId), person1.getId()); if (pRoleCombined != null) pRoleCombined = criteriaBuilder.and(pRoleCombined, sponsorP); else pRoleCombined = sponsorP; } else { pRoleCombined = criteriaBuilder.or(); } } if (roleExpDate != null) { Predicate expDateP = criteriaBuilder.between(role.get(JpaRoleImpl_.end), new Date(), roleExpDate); if (pRoleCombined != null) pRoleCombined = criteriaBuilder.and(pRoleCombined, expDateP); else pRoleCombined = expDateP; } Predicate pComplete = criteriaBuilder.and(); if (pBirthDate != null) pComplete = criteriaBuilder.and(pComplete, pBirthDate); if (combined != null) pComplete = criteriaBuilder.and(pComplete, combined); if (pRoleCombined != null) pComplete = criteriaBuilder.and(pComplete, pRoleCombined); c.select(person).where(pComplete); // if (pBirthDate != null && combined != null) { // c.select(person).where(criteriaBuilder.and(pBirthDate, combined)); // } else if (pBirthDate != null) { // c.select(person).where(pBirthDate); // } else { // c.select(person).where(combined); // } final List<JpaPersonImpl> persons = this.entityManager.createQuery(c).setMaxResults(MAX_QUERY_LIMIT) .getResultList(); return new ArrayList<Person>(persons); }
From source file:com.yunguchang.data.ApplicationRepository.java
private TSysOrgEntity findRightFleetOfCoordinator(String coordinatorId) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<TSysOrgEntity> cq = cb.createQuery(TSysOrgEntity.class); Root<TBusBusinessRelaEntity> mapRoot = cq.from(TBusBusinessRelaEntity.class); Root<TSysUserEntity> userRoot = cq.from(TSysUserEntity.class); cq.select(mapRoot.get(TBusBusinessRelaEntity_.fleet)); Path<TSysOrgEntity> coordinatorOrg = userRoot.get(TSysUserEntity_.department); cq.where(cb.or(cb.and(cb.like(coordinatorOrg.get(TSysOrgEntity_.orgid), "001%" ), cb.equal(mapRoot.get(TBusBusinessRelaEntity_.fleet), coordinatorOrg)), cb.and(cb.notLike(coordinatorOrg.get(TSysOrgEntity_.orgid), "001%"), cb.equal(mapRoot.get(TBusBusinessRelaEntity_.busOrg), coordinatorOrg)) ),//from w w w . j a v a 2 s. c om cb.equal(userRoot.get(TSysUserEntity_.userid), coordinatorId) ); return Iterables.getFirst(em.createQuery(cq).getResultList(), null); }
From source file:eu.domibus.common.dao.ErrorLogDao.java
public List<ErrorLogEntry> findPaged(int from, int max, String column, boolean asc, HashMap<String, Object> filters) { CriteriaBuilder cb = this.em.getCriteriaBuilder(); CriteriaQuery<ErrorLogEntry> cq = cb.createQuery(ErrorLogEntry.class); Root<ErrorLogEntry> ele = cq.from(ErrorLogEntry.class); cq.select(ele);//from www . j ava2 s . c o m List<Predicate> predicates = new ArrayList<Predicate>(); for (Map.Entry<String, Object> filter : filters.entrySet()) { if (filter.getValue() != null) { if (filter.getValue() instanceof String) { if (!filter.getValue().toString().isEmpty()) { switch (filter.getKey().toString()) { case "": break; case "timestampFrom": predicates.add(cb.greaterThanOrEqualTo(ele.<Date>get("timestamp"), Timestamp.valueOf(filter.getValue().toString()))); break; case "timestampTo": predicates.add(cb.lessThanOrEqualTo(ele.<Date>get("timestamp"), Timestamp.valueOf(filter.getValue().toString()))); break; case "notifiedFrom": predicates.add(cb.greaterThanOrEqualTo(ele.<Date>get("notified"), Timestamp.valueOf(filter.getValue().toString()))); break; case "notifiedTo": predicates.add(cb.lessThanOrEqualTo(ele.<Date>get("notified"), Timestamp.valueOf(filter.getValue().toString()))); break; default: predicates.add(cb.like(ele.<String>get(filter.getKey()), (String) filter.getValue())); break; } } } else { predicates.add(cb.equal(ele.<String>get(filter.getKey()), filter.getValue())); } } } cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()]))); if (column != null) { if (asc) { cq.orderBy(cb.asc(ele.get(column))); } else { cq.orderBy(cb.desc(ele.get(column))); } } final TypedQuery<ErrorLogEntry> query = this.em.createQuery(cq); query.setFirstResult(from); query.setMaxResults(max); return query.getResultList(); }
From source file:cn.buk.hotel.dao.HotelDaoImpl.java
@Override public List<HotelInfo> searchAvailableHotel(HotelSearchCriteria sc) { List<HotelInfo> hotelInfos = null; try {// w w w. j a v a2 s .co m //body CriteriaBuilder cb = getEm().getCriteriaBuilder(); CriteriaQuery<HotelInfo> cq = cb.createQuery(HotelInfo.class); Root<HotelInfo> root = cq.from(HotelInfo.class); root.alias("h"); List<Predicate> predicates = new ArrayList<Predicate>(); Predicate predicate = cb.equal(root.get(HotelInfo_.cityId), sc.getCityId()); predicates.add(predicate); /** * ratePlanStatus-1???) yfddai 2015-1-8 */ predicate = cb.notEqual(root.get(HotelInfo_.ratePlanStatus), -1); predicates.add(predicate); if (sc.getDistrictId() > 0) { predicate = cb.equal(root.get(HotelInfo_.areaId), sc.getDistrictId()); predicates.add(predicate); } if (sc.getHotelName() != null && sc.getHotelName().trim().length() > 0) { predicate = cb.like(root.get(HotelInfo_.hotelName), "%" + sc.getHotelName() + "%"); predicates.add(predicate); } if (sc.getStar() != null && sc.getStar().length() > 0) { Join<HotelInfo, HotelAward> hotelAward = root.join("hotelAwards", JoinType.LEFT); hotelAward.alias("ha"); predicates.add(cb.equal(hotelAward.get("provider"), "HotelStarRate")); String[] stars = sc.getStar().split(","); Predicate p0 = cb.disjunction(); for (String star : stars) { if (star.length() == 0) continue; int starLevel = Integer.parseInt(star); if (starLevel == 2) p0 = cb.or(p0, cb.le(hotelAward.get(HotelAward_.rating), starLevel)); else p0 = cb.or(p0, cb.equal(hotelAward.get("rating"), starLevel)); } predicates.add(p0); } if (sc.getZoneId() > 0) { Join<HotelInfo, HotelAddressZone> hotelZone = root.join(HotelInfo_.hotelAddressZones, JoinType.LEFT); hotelZone.alias("hz"); predicate = cb.equal(hotelZone.get(HotelAddressZone_.zoneCode), sc.getZoneId()); predicates.add(predicate); } // count items CriteriaQuery<Long> cq0 = cb.createQuery(Long.class); Root<HotelInfo> root0 = cq0.from(HotelInfo.class); root0.alias("h"); if (sc.getStar() != null && sc.getStar().length() > 0) { Join<HotelInfo, HotelAward> hotelAward0 = root0.join("hotelAwards", JoinType.LEFT); hotelAward0.alias("ha"); } if (sc.getZoneId() > 0) { Join<HotelInfo, HotelAddressZone> hotelZone0 = root0.join(HotelInfo_.hotelAddressZones, JoinType.LEFT); hotelZone0.alias("hz"); } cq0.select(cb.count(root0)).where(predicates.toArray(new Predicate[0])); Long count = getEm().createQuery(cq0).getSingleResult(); sc.getPage().setRowCount(count.intValue()); int firstPosition = (sc.getPage().getPageNo() - 1) * sc.getPage().getPageSize(); cq.select(root).where(predicates.toArray(new Predicate[0])); hotelInfos = getEm().createQuery(cq).setFirstResult(firstPosition) .setMaxResults(sc.getPage().getPageSize()).getResultList(); } catch (PersistenceException e) { logger.error(e.getMessage()); } return hotelInfos == null ? new ArrayList<HotelInfo>() : hotelInfos; }
From source file:net.awired.generic.jpa.dao.impl.GenericDaoImpl.java
private Predicate[] BuildFilterPredicates(Root<ENTITY> root, String search, List<String> searchProperties) { if (Strings.isNullOrEmpty(search)) { return new Predicate[] {}; }/* w w w.j a v a 2s. c o m*/ CriteriaBuilder builder = entityManager.getCriteriaBuilder(); EntityType<ENTITY> type = entityManager.getMetamodel().entity(entityClass); String[] split = search.split(","); Set<SingularAttribute<? super ENTITY, ?>> attributes = type.getSingularAttributes(); List<Predicate> predicates = new ArrayList<Predicate>(split.length * attributes.size()); for (String searchElem : split) { String searchProperty = null; if (searchElem.contains(":")) { String[] propSearchs = searchElem.trim().split(":", 2); searchElem = propSearchs[1]; searchProperty = propSearchs[0]; } boolean numeric; try { Double.parseDouble(searchElem); numeric = true; } catch (Exception e) { numeric = false; } for (SingularAttribute<? super ENTITY, ?> attribute : attributes) { if (searchProperties != null && !searchProperties.isEmpty() && !searchProperties.contains(attribute.getName())) { continue; // skip this property as its not listed in searchable properties } if (searchProperty != null && !searchProperty.equals(attribute.getName())) { continue; // skip this property as we are searching for specific property } Class<?> javaType = attribute.getJavaType(); if (javaType == String.class) { @SuppressWarnings("unchecked") Predicate like = builder.like( builder.lower(root.get((SingularAttribute<ENTITY, String>) attribute)), "%" + searchElem.toLowerCase().trim() + "%"); predicates.add(like); } else if (numeric && (Number.class.isAssignableFrom(javaType) || javaType == int.class || javaType == short.class || javaType == long.class || javaType == float.class || javaType == double.class || javaType == byte.class)) { Predicate like = builder.equal(root.get(attribute), searchElem.toLowerCase().trim()); predicates.add(like); } //TODO fancy types // enums // char // boolean } } return predicates.toArray(new Predicate[] {}); }
From source file:com.yunguchang.data.ApplicationRepository.java
public List<TAzCarinfoEntity> listAllCandidateCars(String[] applicationIds, String keyword, Integer offset, Integer limit, PrincipalExt principalExt) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<TAzCarinfoEntity> cq = cb.createQuery(TAzCarinfoEntity.class); Root<TAzCarinfoEntity> carRoot = cq.from(TAzCarinfoEntity.class); carRoot.fetch(TAzCarinfoEntity_.driver, JoinType.LEFT); cq.select(carRoot);/*w w w.ja v a 2 s .c o m*/ Subquery<TBusScheduleCarEntity> overlapScheduleCarSubQuery = cq.subquery(TBusScheduleCarEntity.class); applyOverlapScheduleCarSubquery(overlapScheduleCarSubQuery, applicationIds, carRoot, null, cb, principalExt); Predicate predicate = cb.and(cb.equal(carRoot.get(TAzCarinfoEntity_.clzt), "02"), cb.or(cb.equal(carRoot.get(TAzCarinfoEntity_.repairingState), RepairingState.NONE.id()), cb.isNull(carRoot.get(TAzCarinfoEntity_.repairingState)) ), cb.not(cb.exists(overlapScheduleCarSubQuery)) ); if (keyword != null) { predicate = cb.and(predicate, cb.or(cb.like(carRoot.get(TAzCarinfoEntity_.sysOrg).get(TSysOrgEntity_.orgname), "%" + keyword + "%"), cb.like(carRoot.get(TAzCarinfoEntity_.cphm), "%" + keyword + "%"))); } cq.where(predicate); cq.orderBy(cb.asc(carRoot.get(TAzCarinfoEntity_.cphm))); TypedQuery<TAzCarinfoEntity> query = em.createQuery(cq); if (offset != null) { query.setFirstResult(offset); } if (limit != null) { query.setMaxResults(limit); } applySecurityFilter("cars", principalExt); return query.getResultList(); }
From source file:org.openmeetings.app.data.user.Usermanagement.java
/** * suche eines Bentzers/*from w ww . j ava 2 s .co m*/ * * @param user_level * @param searchstring * @param max * @param start * @return */ public List<Users> searchUser(long user_level, String searchcriteria, String searchstring, int max, int start, String orderby, boolean asc) { if (authLevelManagement.checkAdminLevel(user_level)) { try { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Users> cq = cb.createQuery(Users.class); Root<Users> c = cq.from(Users.class); Expression<String> literal = cb.literal("%" + searchstring + "%"); // crit.add(Restrictions.ilike(searchcriteria, "%" + // searchstring + "%")); Path<String> path = c.get(searchcriteria); Predicate predicate = cb.like(path, literal); Predicate condition = cb.notEqual(c.get("deleted"), "true"); cq.where(condition, predicate); cq.distinct(asc); if (asc) { cq.orderBy(cb.asc(c.get(orderby))); } else { cq.orderBy(cb.desc(c.get(orderby))); } TypedQuery<Users> q = em.createQuery(cq); q.setFirstResult(start); q.setMaxResults(max); List<Users> contactsZ = q.getResultList(); return contactsZ; } catch (Exception ex2) { log.error("searchUser", ex2); } } return null; }
From source file:org.oncoblocks.centromere.jpa.QueryCriteriaSpecification.java
public Predicate toPredicate(Root<T> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) { String key = queryCriteria.getKey(); Object value = queryCriteria.getValue(); Evaluation eval = queryCriteria.getEvaluation(); Path path = null;/*from w w w. j a v a 2s . c om*/ if (key.contains(".")) { String[] bits = key.split("\\."); path = root.join(bits[0]).get(bits[1]); } else { path = root.get(key); } logger.debug(String.format("[CENTROMERE] Converting QueryCriteria to JPA specification: %s", queryCriteria.toString())); switch (eval) { case EQUALS: return criteriaBuilder.equal(path, value); case NOT_EQUALS: return criteriaBuilder.notEqual(path, value); case IN: return path.in(value); case NOT_IN: return criteriaBuilder.not(path.in(value)); case IS_NULL: return criteriaBuilder.isNull(path); case NOT_NULL: return criteriaBuilder.isNotNull(path); case GREATER_THAN: return criteriaBuilder.greaterThan(path, value.toString()); case GREATER_THAN_EQUALS: return criteriaBuilder.greaterThanOrEqualTo(path, value.toString()); case LESS_THAN: return criteriaBuilder.lessThan(path, value.toString()); case LESS_THAN_EQUALS: return criteriaBuilder.lessThanOrEqualTo(path, value.toString()); case BETWEEN: return criteriaBuilder.and(criteriaBuilder.greaterThan(path, ((List<?>) value).get(0).toString()), criteriaBuilder.lessThan(path, ((List<?>) value).get(1).toString())); case OUTSIDE: return criteriaBuilder.or(criteriaBuilder.greaterThan(path, ((List<?>) value).get(1).toString()), criteriaBuilder.lessThan(path, ((List<?>) value).get(0).toString())); case BETWEEN_INCLUSIVE: return criteriaBuilder.and( criteriaBuilder.greaterThanOrEqualTo(path, ((List<?>) value).get(0).toString()), criteriaBuilder.lessThanOrEqualTo(path, ((List<?>) value).get(1).toString())); case OUTSIDE_INCLUSIVE: return criteriaBuilder.or( criteriaBuilder.greaterThanOrEqualTo(path, ((List<?>) value).get(1).toString()), criteriaBuilder.lessThanOrEqualTo(path, ((List<?>) value).get(0).toString())); case LIKE: return criteriaBuilder.like(path, "%" + value.toString() + "%"); case NOT_LIKE: return criteriaBuilder.notLike(path, "%" + value.toString() + "%"); case STARTS_WITH: return criteriaBuilder.like(path, value.toString() + "%"); case ENDS_WITH: return criteriaBuilder.like(path, "%" + value.toString()); default: return criteriaBuilder.equal(root.get(queryCriteria.getKey()), queryCriteria.getValue()); } }
From source file:com.yunguchang.data.ApplicationRepository.java
public List<TRsDriverinfoEntity> listAllCandidateDrivers(String[] applicationIds, String carId, String keyword, Integer offset, Integer limit, PrincipalExt principalExt) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<TRsDriverinfoEntity> cq = cb.createQuery(TRsDriverinfoEntity.class); Root<TRsDriverinfoEntity> driverRoot = cq.from(TRsDriverinfoEntity.class); Root<TAzCarinfoEntity> carRoot = cq.from(TAzCarinfoEntity.class); cq.select(driverRoot);//from w w w. j a v a2 s.co m Subquery<TBusScheduleCarEntity> overlapScheduleCarSubQuery = cq.subquery(TBusScheduleCarEntity.class); applyOverlapScheduleCarSubquery(overlapScheduleCarSubQuery, applicationIds, carRoot, driverRoot, cb, principalExt); Subquery<TRsDriverinfoEntity> subqueryLicense = cq.subquery(TRsDriverinfoEntity.class); Root<TAzJzRelaEntity> licenseMapping = subqueryLicense.from(TAzJzRelaEntity.class); subqueryLicense.select(driverRoot); subqueryLicense.where( cb.equal(carRoot.get(TAzCarinfoEntity_.xszcx), licenseMapping.get(TAzJzRelaEntity_.xszcx)), cb.equal(licenseMapping.get(TAzJzRelaEntity_.jzyq), driverRoot.get(TRsDriverinfoEntity_.drivecartype))); Predicate predicate = cb.and(cb.equal(carRoot.get(TAzCarinfoEntity_.id), carId), cb.equal(driverRoot.get(TRsDriverinfoEntity_.department), carRoot.get(TAzCarinfoEntity_.sysOrg)), cb.equal(driverRoot.get(TRsDriverinfoEntity_.enabled), "1"), cb.or(cb.exists(subqueryLicense), cb.isNull(driverRoot.get(TRsDriverinfoEntity_.drivecartype)) ), cb.not(cb.exists(overlapScheduleCarSubQuery)) ); if (keyword != null) { predicate = cb.and(predicate, cb.or(cb.like(driverRoot.get(TRsDriverinfoEntity_.drivername), "%" + keyword + "%"))); } cq.where(predicate); cq.orderBy(cb .asc(cb.function("casttogbk", String.class, cb.trim(driverRoot.get(TRsDriverinfoEntity_.drivername)) ))); TypedQuery<TRsDriverinfoEntity> query = em.createQuery(cq); if (offset != null) { query.setFirstResult(offset); } if (limit != null) { query.setMaxResults(limit); } return query.getResultList(); }
From source file:ca.uhn.fhir.jpa.dao.BaseFhirResourceDao.java
private Predicate createPredicateString(IQueryParameterType theParameter, String theParamName, CriteriaBuilder theBuilder, From<ResourceIndexedSearchParamString, ResourceIndexedSearchParamString> theFrom) { String rawSearchTerm;/* w ww . j av a 2s .co m*/ if (theParameter instanceof TokenParam) { TokenParam id = (TokenParam) theParameter; if (!id.isText()) { throw new IllegalStateException("Trying to process a text search on a non-text token parameter"); } rawSearchTerm = id.getValue(); } else if (theParameter instanceof StringParam) { StringParam id = (StringParam) theParameter; rawSearchTerm = id.getValue(); } else if (theParameter instanceof IPrimitiveDatatype<?>) { IPrimitiveDatatype<?> id = (IPrimitiveDatatype<?>) theParameter; rawSearchTerm = id.getValueAsString(); } else { throw new IllegalArgumentException("Invalid token type: " + theParameter.getClass()); } if (rawSearchTerm.length() > ResourceIndexedSearchParamString.MAX_LENGTH) { throw new InvalidRequestException("Parameter[" + theParamName + "] has length (" + rawSearchTerm.length() + ") that is longer than maximum allowed (" + ResourceIndexedSearchParamString.MAX_LENGTH + "): " + rawSearchTerm); } String likeExpression = normalizeString(rawSearchTerm); likeExpression = likeExpression.replace("%", "[%]") + "%"; Predicate singleCode = theBuilder.like(theFrom.get("myValueNormalized").as(String.class), likeExpression); if (theParameter instanceof StringParam && ((StringParam) theParameter).isExact()) { Predicate exactCode = theBuilder.equal(theFrom.get("myValueExact"), rawSearchTerm); singleCode = theBuilder.and(singleCode, exactCode); } return singleCode; }