List of usage examples for javax.persistence.criteria CriteriaBuilder literal
<T> Expression<T> literal(T value);
From source file:org.ngrinder.agent.repository.AgentManagerSpecification.java
/** * Query specification to query the agent existing in the specified region. * * @param region region to query/*from w w w. j av a 2 s . c o m*/ * @return Specification of this query */ public static Specification<AgentInfo> startWithRegion(final String region) { return new Specification<AgentInfo>() { @Override public Predicate toPredicate(Root<AgentInfo> root, CriteriaQuery<?> query, CriteriaBuilder cb) { Expression<String> regionField = root.get("region").as(String.class); return cb.or(cb.like(regionField, region + "/_owned%", cb.literal('/')), cb.equal(regionField, region)); } }; }
From source file:net.kaczmarzyk.spring.data.jpa.domain.EmptyResultOnTypeMismatch.java
@Override public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb) { try {//from ww w . ja v a 2 s .c o m return wrappedSpec.toPredicate(root, query, cb); } catch (ValueRejectedException e) { return cb.equal(cb.literal(0), cb.literal(1)); } }
From source file:net.dontdrinkandroot.persistence.dao.NumericEntityDaoTest.java
@Test @Transactional//from ww w .j av a2 s. c om public void testQuot() { NumericEntity entity2 = new NumericEntity(); entity2.setLongField(2L); entity2.setIntField(3); entity2 = this.save(entity2); final CriteriaBuilder builder = this.getCriteriaBuilder(); final CriteriaQuery<Number> criteriaQuery = builder.createQuery(Number.class); final Root<NumericEntity> root = criteriaQuery.from(NumericEntity.class); final Expression<Number> quot = builder.quot( builder.prod(builder.literal(1f), root.get(NumericEntity_.intField)), root.get(NumericEntity_.longField)); criteriaQuery.select(quot); final Number result = this.findSingle(criteriaQuery); Assert.assertEquals(Float.class, result.getClass()); Assert.assertEquals(3 / 2f, result); }
From source file:eu.uqasar.service.user.UserService.java
public List<User> getAllExceptAndFilter(Collection<User> usersToExclude, final String filter) { if (usersToExclude == null || usersToExclude.isEmpty()) { return this.getAll(); }// ww w . j a va 2 s .c o m logger.infof("loading all Users except %s ...", usersToExclude); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<User> query = cb.createQuery(User.class); Root<User> root = query.from(User.class); if (filter != null && !filter.isEmpty()) { Expression<String> literal = cb.upper(cb.literal(LIKE_WILDCARD + filter + LIKE_WILDCARD)); Predicate likeFirstName = cb.like(cb.upper(root.get(User_.firstName)), literal); Predicate likeLastName = cb.like(cb.upper(root.get(User_.lastName)), literal); Predicate likeUserName = cb.like(cb.upper(root.get(User_.userName)), literal); Predicate orLikeName = cb.or(likeFirstName, likeLastName, likeUserName); query.where(cb.and(cb.not(root.in(usersToExclude)), orLikeName)); } else { query.where(cb.not(root.in(usersToExclude))); } return em.createQuery(query).getResultList(); }
From source file:org.zlogic.vogon.web.data.TransactionFilterSpecification.java
/** * Builds the Predicate/*from w w w . j a v a 2s. c o m*/ * * @param root the FinanceTransaction query root * @param cq the CriteriaQuery instance * @param cb the CriteriaBuilder instance * @return the Predicate of this filter */ @Override public Predicate toPredicate(Root<FinanceTransaction> root, CriteriaQuery<?> cq, CriteriaBuilder cb) { Predicate ownerPredicate = cb.equal(root.get(FinanceTransaction_.owner), owner); Predicate descriptionPredicate = filterDescription != null ? cb.like(cb.lower(root.get(FinanceTransaction_.description)), filterDescription.toLowerCase()) : cb.conjunction(); Predicate tagsPredicate = cb.conjunction(); if (filterTags != null && !filterTags.isEmpty()) { Set<String> filterTagsLowercase = new HashSet<>(); for (String tag : filterTags) filterTagsLowercase.add(tag.toLowerCase()); tagsPredicate = cb.lower(root.join(FinanceTransaction_.tags)).in(cb.literal(filterTagsLowercase)); } Predicate datePredicate = filterDate != null ? cb.equal(root.get(FinanceTransaction_.transactionDate), new java.sql.Date(filterDate.getTime())) : cb.conjunction(); return cb.and(ownerPredicate, descriptionPredicate, datePredicate, tagsPredicate); }
From source file:de.whs.poodle.repositories.StatisticsRepository.java
public List<Statistic> getStatistics(FeedbackSearchCriteria s, int instructorId, int limit) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Statistic> cq = cb.createQuery(Statistic.class); Root<Statistic> statistic = cq.from(Statistic.class); /* fetch the exercises immediately so they don't have to * be lazy-fetched one by one while rendering the table rows. */ statistic.fetch("exercise"); // join we need to match the course Join<Statistic, Course> course = statistic.join("courseTerm").join("course"); // create empty "and" predicate Predicate where = cb.conjunction(); // only non-empty Predicate notEmpty = cb.isFalse(statistic.get("empty")); where = cb.and(where, notEmpty);//from w w w .ja v a 2s .c om // only statistics for courses that the instructor has access to Predicate hasInstructorAccessToCourse = cb.isTrue(cb.function("has_instructor_access_to_course", Boolean.class, course.get("id"), cb.literal(instructorId))); where = cb.and(where, hasInstructorAccessToCourse); // filter by courseId if (s.getCourseId() != 0) { Predicate courseMatches = cb.equal(course.get("id"), s.getCourseId()); where = cb.and(where, courseMatches); } // filter by student if (s.getStudent() != null) { Predicate studentMatches = cb.equal(statistic.get("student").get("id"), s.getStudent().getId()); where = cb.and(where, studentMatches); } cq.where(where); // order by date cq.orderBy(cb.desc(statistic.get("completedAt"))); return em.createQuery(cq).setMaxResults(limit).getResultList(); }
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);//w w w .j a v a2 s . c o m 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:org.openmeetings.app.data.user.Usermanagement.java
/** * suche eines Bentzers/*from w w w. j av a 2 s . c om*/ * * @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:ch.puzzle.itc.mobiliar.business.server.boundary.ServerView.java
public List<ServerTuple> getNodeServers(String hostFilter, String appServerFilter, String runtimeFilter, String nodeFilter, String contextFilter) { CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery<ServerTuple> q = cb.createQuery(ServerTuple.class); //get Node ResType Root<ResourceEntity> node = q.from(ResourceEntity.class); Join<ResourceEntity, ResourceTypeEntity> nodeType = node.join("resourceType", JoinType.LEFT); Join<ResourceEntity, ReleaseEntity> nodeRelease = node.join("release", JoinType.LEFT); //get Props on node Join<ResourceEntity, ResourceContextEntity> resCtx = node.join("contexts", JoinType.LEFT); Join<ResourceContextEntity, ContextEntity> nodeCtx = resCtx.join("context", JoinType.LEFT); Join<ContextEntity, ContextEntity> nodeDomain = nodeCtx.join("parent", JoinType.LEFT); Join<ResourceContextEntity, PropertyEntity> nodeProp = resCtx.join("properties", JoinType.LEFT); Join<PropertyEntity, PropertyDescriptorEntity> nodePropType = nodeProp.join("descriptor", JoinType.LEFT); //get AppServer Join<ResourceEntity, ConsumedResourceRelationEntity> nodeResRel = node.join("consumedSlaveRelations", JoinType.LEFT);//from www . j av a 2 s . c o m Join<ConsumedResourceRelationEntity, ResourceEntity> appServer = nodeResRel.join("masterResource", JoinType.LEFT); Join<ResourceEntity, ReleaseEntity> asRelease = appServer.join("release", JoinType.LEFT); Join<ResourceEntity, ResourceTypeEntity> asType = appServer.join("resourceType", JoinType.LEFT); //get Runtime of as Join<ResourceEntity, ConsumedResourceRelationEntity> asResRel = appServer.join("consumedMasterRelations", JoinType.LEFT); Join<ConsumedResourceRelationEntity, ResourceEntity> asRuntime = asResRel.join("slaveResource", JoinType.LEFT); Join<ResourceEntity, ResourceTypeEntity> runtimeType = asRuntime.join("resourceType", JoinType.LEFT); q.select(cb.construct(ServerTuple.class, nodeProp.get("value"), appServer.get("name"), appServer.get("id"), asRelease.get("name"), asRuntime.get("name"), node.get("name"), node.get("id"), nodeRelease.get("name"), nodeDomain.get("name"), nodeDomain.get("id"), nodeCtx.get("name"), nodeCtx.get("id"), cb.literal(1) // true )); Predicate p = cb.and(cb.equal(nodeType.get("name"), DefaultResourceTypeDefinition.NODE.name()), cb.or(cb.equal(asType.get("name"), DefaultResourceTypeDefinition.APPLICATIONSERVER.name()), cb.isNull(asType.get("name")) //nodes without appServer ), cb.or(cb.equal(runtimeType.get("name"), ResourceTypeEntity.RUNTIME), cb.isNull(runtimeType.get("name"))), cb.isNotNull(nodeProp.get("value")), cb.equal(nodePropType.get("propertyName"), "hostName") ); p = addFilters(p, cb, hostFilter, appServerFilter, runtimeFilter, nodeFilter, contextFilter, nodeProp.<String>get("value"), appServer.<String>get("name"), asRuntime.<String>get("name"), node.<String>get("name"), nodeCtx.<String>get("name")); q.where(p); TypedQuery<ServerTuple> query = entityManager.createQuery(q); List<ServerTuple> servers = query.getResultList(); return servers; }
From source file:ch.puzzle.itc.mobiliar.business.server.boundary.ServerView.java
public List<ServerTuple> getAppServers(String hostFilter, String appServerFilter, String runtimeFilter, String nodeFilter, String contextFilter) { CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery<ServerTuple> q = cb.createQuery(ServerTuple.class); //get Node ResType Root<ResourceEntity> node = q.from(ResourceEntity.class); Join<ResourceEntity, ResourceTypeEntity> nodeType = node.join("resourceType", JoinType.LEFT); Join<ResourceEntity, ReleaseEntity> nodeRelease = node.join("release", JoinType.LEFT); //get AppServer Join<ResourceEntity, ConsumedResourceRelationEntity> nodeResRel = node.join("consumedSlaveRelations", JoinType.LEFT);//from w w w.j a v a2s. co m Join<ConsumedResourceRelationEntity, ResourceEntity> appServer = nodeResRel.join("masterResource", JoinType.LEFT); Join<ResourceEntity, ReleaseEntity> asRelease = appServer.join("release", JoinType.LEFT); Join<ResourceEntity, ResourceTypeEntity> asType = appServer.join("resourceType", JoinType.LEFT); //get Runtime of as Join<ResourceEntity, ConsumedResourceRelationEntity> asResRel = appServer.join("consumedMasterRelations", JoinType.LEFT); Join<ConsumedResourceRelationEntity, ResourceEntity> asRuntime = asResRel.join("slaveResource", JoinType.LEFT); Join<ResourceEntity, ResourceTypeEntity> runtimeType = asRuntime.join("resourceType", JoinType.LEFT); //get Props between as and node Join<ConsumedResourceRelationEntity, ResourceRelationContextEntity> resRelCtx = nodeResRel.join("contexts", JoinType.LEFT); Join<ResourceRelationContextEntity, ContextEntity> asCtx = resRelCtx.join("context", JoinType.LEFT); Join<ContextEntity, ContextEntity> asDomain = asCtx.join("parent", JoinType.LEFT); Join<ResourceRelationContextEntity, PropertyEntity> asProp = resRelCtx.join("properties", JoinType.LEFT); //here an on clause should be added, so we don't get hostnames that are divined directly on the node multiple times (and descriptor.propertyName = 'hostName') //on support was added in jpa 2.1 which is part of JEE 7 Join<PropertyEntity, PropertyDescriptorEntity> asPropType = asProp.join("descriptor", JoinType.LEFT); q.select(cb.construct(ServerTuple.class, asProp.get("value"), appServer.get("name"), appServer.get("id"), asRelease.get("name"), asRuntime.get("name"), node.get("name"), node.get("id"), nodeRelease.get("name"), asDomain.get("name"), asDomain.get("id"), asCtx.get("name"), asCtx.get("id"), cb.literal(0) //false )); Predicate p = cb.and(cb.equal(nodeType.get("name"), DefaultResourceTypeDefinition.NODE.name()), cb.equal(asType.get("name"), DefaultResourceTypeDefinition.APPLICATIONSERVER.name()), cb.or(cb.equal(runtimeType.get("name"), ResourceTypeEntity.RUNTIME), cb.isNull(runtimeType.get("name"))), cb.isNotNull(asProp.get("value")), cb.equal(asPropType.get("propertyName"), "hostName")); p = addFilters(p, cb, hostFilter, appServerFilter, runtimeFilter, nodeFilter, contextFilter, asProp.<String>get("value"), appServer.<String>get("name"), asRuntime.<String>get("name"), node.<String>get("name"), asCtx.<String>get("name")); q.where(p); TypedQuery<ServerTuple> query = entityManager.createQuery(q); List<ServerTuple> servers = query.getResultList(); return servers; }