List of usage examples for javax.persistence.criteria CriteriaBuilder like
Predicate like(Expression<String> x, String pattern);
From source file:de.egore911.hexanalyzer.persistence.selector.PluginSelector.java
@Nonnull @Override// w ww .j av a 2 s . c om protected List<Predicate> generatePredicateList(@Nonnull CriteriaBuilder builder, @Nonnull Root<PluginEntity> from, @Nonnull CriteriaQuery<?> criteriaQuery) { List<Predicate> predicates = super.generatePredicateList(builder, from, criteriaQuery); if (extensionPoint != null) { builder.equal(from.get(PluginEntity_.extensionPoint), extensionPoint); } if (StringUtils.isNotEmpty(search)) { String likePattern = '%' + search + '%'; predicates.add(builder.or(builder.like(from.get(PluginEntity_.qualifiedName), likePattern), builder.like(from.get(PluginEntity_.source), likePattern))); } return predicates; }
From source file:com.ims.service.OrderService.java
public List<PurchaseOrder> searchPurchaseOrderList(final OrderSearchCriteria orderSearchCriteria) { List<PurchaseOrder> purchaseOrders = new ArrayList<PurchaseOrder>(); Specification<PurchaseOrder> speci = new Specification<PurchaseOrder>() { @Override// w w w . j a v a2s .com public Predicate toPredicate(Root<PurchaseOrder> root, CriteriaQuery<?> query, CriteriaBuilder cb) { List<Predicate> predicates = new ArrayList<Predicate>(); if (StringUtils.isNotEmpty(orderSearchCriteria.getPurchaseOrderStatus())) { predicates.add(cb.equal(root.get("status"), orderSearchCriteria.getPurchaseOrderStatus())); } if (StringUtils.isNotEmpty(orderSearchCriteria.getPurchaseOrderNum())) { predicates.add(cb.like(root.<String>get("purchaseOrderNumber"), "%" + orderSearchCriteria.getPurchaseOrderNum() + "%")); } if (StringUtils.isNotEmpty(orderSearchCriteria.getProformaInvoiceNum())) { predicates.add(cb.like(root.<String>get("piNumber"), "%" + orderSearchCriteria.getProformaInvoiceNum() + "%")); } query.where(cb.and(predicates.toArray(new Predicate[predicates.size()]))) .orderBy(cb.desc(root.get("changeLog").get("createdDate"))); return null; } }; return purchaseOrderRepository.findAll(speci); }
From source file:com.netflix.genie.core.jpa.specifications.JpaJobSpecs.java
/** * Generate a criteria query predicate for a where clause based on the given parameters. * * @param root The root to use/*w w w .j a v a2 s. com*/ * @param cb The criteria builder to use * @param id The job id * @param name The job name * @param user The user who created the job * @param statuses The job statuses * @param tags The tags for the jobs to find * @param clusterName The cluster name * @param cluster The cluster the job should have been run on * @param commandName The command name * @param command The command the job should have been run with * @param minStarted The time which the job had to start after in order to be return (inclusive) * @param maxStarted The time which the job had to start before in order to be returned (exclusive) * @param minFinished The time which the job had to finish after in order to be return (inclusive) * @param maxFinished The time which the job had to finish before in order to be returned (exclusive) * @return The specification */ public static Predicate getFindPredicate(final Root<JobEntity> root, final CriteriaBuilder cb, final String id, final String name, final String user, final Set<JobStatus> statuses, final Set<String> tags, final String clusterName, final ClusterEntity cluster, final String commandName, final CommandEntity command, final Date minStarted, final Date maxStarted, final Date minFinished, final Date maxFinished) { final List<Predicate> predicates = new ArrayList<>(); if (StringUtils.isNotBlank(id)) { predicates.add(JpaSpecificationUtils.getStringLikeOrEqualPredicate(cb, root.get(JobEntity_.id), id)); } if (StringUtils.isNotBlank(name)) { predicates .add(JpaSpecificationUtils.getStringLikeOrEqualPredicate(cb, root.get(JobEntity_.name), name)); } if (StringUtils.isNotBlank(user)) { predicates .add(JpaSpecificationUtils.getStringLikeOrEqualPredicate(cb, root.get(JobEntity_.user), user)); } if (statuses != null && !statuses.isEmpty()) { final List<Predicate> orPredicates = statuses.stream() .map(status -> cb.equal(root.get(JobEntity_.status), status)).collect(Collectors.toList()); predicates.add(cb.or(orPredicates.toArray(new Predicate[orPredicates.size()]))); } if (tags != null && !tags.isEmpty()) { predicates.add(cb.like(root.get(JobEntity_.tags), JpaSpecificationUtils.getTagLikeString(tags))); } if (cluster != null) { predicates.add(cb.equal(root.get(JobEntity_.cluster), cluster)); } if (StringUtils.isNotBlank(clusterName)) { predicates.add(JpaSpecificationUtils.getStringLikeOrEqualPredicate(cb, root.get(JobEntity_.clusterName), clusterName)); } if (command != null) { predicates.add(cb.equal(root.get(JobEntity_.command), command)); } if (StringUtils.isNotBlank(commandName)) { predicates.add(JpaSpecificationUtils.getStringLikeOrEqualPredicate(cb, root.get(JobEntity_.commandName), commandName)); } if (minStarted != null) { predicates.add(cb.greaterThanOrEqualTo(root.get(JobEntity_.started), minStarted)); } if (maxStarted != null) { predicates.add(cb.lessThan(root.get(JobEntity_.started), maxStarted)); } if (minFinished != null) { predicates.add(cb.greaterThanOrEqualTo(root.get(JobEntity_.finished), minFinished)); } if (maxFinished != null) { predicates.add(cb.lessThan(root.get(JobEntity_.finished), maxFinished)); } return cb.and(predicates.toArray(new Predicate[predicates.size()])); }
From source file:com.sapito.db.dao.AbstractDao.java
public List<T> findBySpecificField(String field, Object fieldContent, String predicates, LinkedHashMap<String, String> ordering, LinkedList<String> grouping) { CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery cq = cb.createQuery(); Root<T> root = cq.from(entityClass); Predicate predicate = null;// ww w .jav a 2 s. c o m if (predicates.equals("equal")) { predicate = cb.equal(root.get(field), fieldContent); } else if (predicates.equals("likelower")) { predicate = cb.like(cb.lower(root.<String>get(field)), fieldContent.toString()); } else if (predicates.equals("like")) { predicate = cb.like(root.<String>get(field), "%" + fieldContent.toString() + "%"); } cq.select(root); cq.where(predicate); if (ordering != null) { Set<String> set = ordering.keySet(); List<Order> orders = new ArrayList<>(); for (String orderingField : set) { Order order; if (ordering.get(orderingField).equals("ASC")) { order = cb.asc(root.get(orderingField)); } else { order = cb.desc(root.get(orderingField)); } orders.add(order); } cq.orderBy(orders); } if (grouping != null) { Iterator iterator = grouping.iterator(); List<Expression> groups = new LinkedList<>(); while (iterator.hasNext()) { groups.add(root.get(iterator.next().toString())); } cq.groupBy(groups); } Query query = entityManager.createQuery(cq); query.setMaxResults(MAX_RECORDS_RETURNED); return query.getResultList(); }
From source file:com.order.erp.web.controller.SystemController.java
@RequestMapping(path = "amoeba", method = RequestMethod.GET) public String amoebaIndex(HttpServletRequest request, @RequestParam(name = "keyword", required = false) String keyword, @PageableDefault(page = 0, size = 10, sort = "id", direction = Direction.ASC) Pageable pageable, ModelMap model) {/*from ww w . j a va 2 s. co m*/ Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); User me = staffService.findByAccountUsername(((UserDetails) principal).getUsername()); Company company = me.getCompany(); final String finalKeyword = keyword; final Company finalCompany = company; Page<Amoeba> page = adminService.findAmoebas(new Specification<Amoeba>() { public Predicate toPredicate(Root<Amoeba> root, CriteriaQuery<?> query, CriteriaBuilder cb) { query.distinct(true); Predicate p1 = cb.equal(root.get("company").as(Company.class), finalCompany); Predicate p2 = cb.conjunction(); if (StringUtils.isNotBlank(finalKeyword)) { p2 = cb.like(root.get("name").as(String.class), "%" + finalKeyword + "%"); } Predicate p_result = cb.and(p1, p2); return p_result; } }, pageable); model.put("user", me); model.put("company", company); model.put("page", page); String json = JSON.toJSONString(page, SerializerFeature.PrettyFormat); System.out.println(json); return "/system/amoeba_list"; }
From source file:com.aimdek.ccm.dao.impl.TransactionRepositoryImpl.java
/** * Adds the filter criteria./*from w w w .jav a2 s. com*/ * * @param userId * the user id * @param filters * the filters * @param builder * the builder * @param root * the root * @param query * the query */ private void addFilterCriteria(long userId, Map<String, Object> filters, CriteriaBuilder builder, Root<Transaction> root, CriteriaQuery query) { List<Predicate> predicates = new ArrayList<Predicate>(); if (!filters.isEmpty()) { for (Entry<String, Object> entry : filters.entrySet()) { if (CommonUtil.isNotNull(root.get(entry.getKey()))) { predicates.add(builder.like(root.<String>get(entry.getKey()), entry.getValue() + MODULO)); } } } if (CommonUtil.isNotNull(userId)) { User user = userRepository.findById(userId); if (CommonUtil.isNotNull(user) && user.getRole().equals(ROLE_CUSTOMER)) { predicates.add(builder.equal(root.<Long>get(FIELDCONSTANT_USERID), user.getId())); } } query.where(predicates.toArray(new Predicate[] {})); }
From source file:com.order.erp.web.controller.SystemController.java
@RequestMapping(path = "staff", method = RequestMethod.GET) public String staffIndex(HttpServletRequest request, @RequestParam(name = "keyword", required = false) String keyword, @PageableDefault(page = 0, size = 10, sort = "id", direction = Direction.ASC) Pageable pageable, ModelMap model) {//from w w w . j av a 2 s . c o m Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); User me = staffService.findByAccountUsername(((UserDetails) principal).getUsername()); Company company = me.getCompany(); //List<User> userList = userService.findUsersByAmoebaId(company.getId()); final User meStaff = me; final String finalKeyword = keyword; final Company finalCompany = company; Page<User> page = staffService.findUsers(new Specification<User>() { public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) { query.distinct(true); Predicate p1 = cb.equal(root.get("company").as(Company.class), finalCompany); Predicate p2 = cb.conjunction(); if (StringUtils.isNotBlank(finalKeyword)) { Predicate p1_like = cb.like(root.get("account").get("username").as(String.class), "%" + finalKeyword + "%"); Predicate p2_like = cb.like(root.get("realname").as(String.class), "%" + finalKeyword + "%"); p2 = cb.or(p1_like, p2_like); } Predicate p3 = cb.notEqual(root.as(User.class), meStaff); Predicate p_result = cb.and(p1, p2, p3); return p_result; } }, pageable); model.put("user", me); model.put("company", company); model.put("page", page); return "/system/staff_list"; }
From source file:org.sloth.persistence.impl.ObservationDaoImpl.java
@Override public Collection<Observation> getByKeyWord(String key) throws NullPointerException { if (key == null) { throw new NullPointerException(); }/*from w ww . ja va 2s.c o m*/ key = "%" + key.trim().replace('*', '%').toUpperCase() + "%"; CriteriaBuilder b = getEntityManager().getCriteriaBuilder(); CriteriaQuery<Observation> q = b.createQuery(Observation.class); Root<Observation> o = q.from(Observation.class); Join<Observation, Categorie> j = o.join(Observation_.categorie); Collection<Observation> result = getEntityManager().createQuery(q.select(o).distinct(true) .where(b.or(b.like(b.upper(j.get(Categorie_.title)), key), b.like(b.upper(j.get(Categorie_.description)), key), b.like(b.upper(o.get(Observation_.title)), key), b.like(b.upper(o.get(Observation_.description)), key)))) .getResultList(); logger.info("Searched for {}. Got {} Results.", key, result.size()); return result; }
From source file:com.alliander.osgp.adapter.ws.infra.specifications.JpaDeviceSpecifications.java
@Override public Specification<Device> hasDeviceIdentification(final String deviceIdentification, final boolean exactMatch) throws ArgumentNullOrEmptyException { if (StringUtils.isEmpty(deviceIdentification)) { throw new ArgumentNullOrEmptyException("deviceIdentification"); }/* w ww. j av a 2 s . c om*/ return new Specification<Device>() { @Override public Predicate toPredicate(final Root<Device> deviceRoot, final CriteriaQuery<?> query, final CriteriaBuilder cb) { if (exactMatch) { return cb.equal(cb.upper(deviceRoot.<String>get("deviceIdentification")), deviceIdentification); } else { return cb.like(cb.upper(deviceRoot.<String>get("deviceIdentification")), deviceIdentification.toUpperCase()); } } }; }
From source file:aode.lx.persistence.DynamicSpecifications.java
public static <T> Specification<T> bySearchFilter(final Collection<SearchFilter> filters, final Class<T> entityClazz) { return new Specification<T>() { @Override// w ww . j a v a 2 s.c o m public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) { if (Collections3.isNotEmpty(filters)) { List<Predicate> predicates = Lists.newArrayList(); List<Predicate> ORpredicates = Lists.newArrayList(); for (SearchFilter filter : filters) { // nested path translate, Task??"user.name"filedName, ?Task.user.name String[] names = StringUtils.split(filter.fieldName, "."); Path expression = root.get(names[0]); for (int i = 1; i < names.length; i++) { expression = expression.get(names[i]); } Object value = filter.value; if (expression.getJavaType().isEnum()) { value = EnumUtils.valueOf(expression.getJavaType(), filter.value.toString()); predicates.add(builder.equal(expression, value)); } else { // logic operator switch (filter.operator) { case EQ: predicates.add(builder.equal(expression, filter.value)); break; case LIKE: predicates.add(builder.like(expression, "%" + filter.value + "%")); break; case GT: predicates.add(builder.greaterThan(expression, (Comparable) filter.value)); break; case LT: predicates.add(builder.lessThan(expression, (Comparable) filter.value)); break; case GTE: predicates.add(builder.greaterThanOrEqualTo(expression, (Comparable) filter.value)); break; case LTE: predicates.add(builder.lessThanOrEqualTo(expression, (Comparable) filter.value)); break; case NEQ: predicates.add(builder.notEqual(expression, filter.value)); break; case NOTNULL: predicates.add(builder.isNotNull(expression)); break; case ISNULL: predicates.add(builder.isNull(expression)); break; case OREQ: ORpredicates.add(builder.equal(expression, filter.value)); break; case ORLIKE: ORpredicates.add(builder.like(expression, "%" + filter.value + "%")); break; case ORGT: ORpredicates.add(builder.greaterThan(expression, (Comparable) filter.value)); break; case ORLT: ORpredicates.add(builder.lessThan(expression, (Comparable) filter.value)); break; case ORGTE: ORpredicates .add(builder.greaterThanOrEqualTo(expression, (Comparable) filter.value)); break; case ORLTE: ORpredicates.add(builder.lessThanOrEqualTo(expression, (Comparable) filter.value)); break; case ORNEQ: ORpredicates.add(builder.notEqual(expression, filter.value)); break; case ORNOTNULL: ORpredicates.add(builder.isNotNull(expression)); break; case ORISNULL: ORpredicates.add(builder.isNull(expression)); break; } } } // ? and ??? if (!predicates.isEmpty() && !ORpredicates.isEmpty()) { return builder.and(builder.and(predicates.toArray(new Predicate[predicates.size()])), builder.or(ORpredicates.toArray(new Predicate[ORpredicates.size()]))); } if (!predicates.isEmpty()) { return builder.and(predicates.toArray(new Predicate[predicates.size()])); } if (!ORpredicates.isEmpty()) { return builder.or(ORpredicates.toArray(new Predicate[ORpredicates.size()])); } } return builder.conjunction(); } }; }