@GET @Produces({"application/xml", "application/json"}) @Path("/recent/region/{regionName}/{orderLineId}") public List<LiveSalesList> findRecentRegionFrom(@PathParam("regionName") String regionName, @PathParam("orderLineId") Integer orderLineId) { CriteriaBuilder cb = getEntityManager().getCriteriaBuilder(); javax.persistence.criteria.CriteriaQuery cq = cb.createQuery(); Root<LiveSalesList> liveSalesList = cq.from(LiveSalesList.class); cq.select(liveSalesList); cq.where(cb.and( cb.equal(liveSalesList.get(LiveSalesList_.region), regionName), cb.gt(liveSalesList.get(LiveSalesList_.orderLineId), orderLineId) )); Query q = getEntityManager().createQuery(cq); q.setMaxResults(500); return q.getResultList(); }
@Override public Predicate toPredicate(Root<TestSuite> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) { Predicate result = null; if (StringUtils.isNotEmpty(filter.getSuite())) { result = criteriaBuilder.like(criteriaBuilder.lower(root.get(SUITE_PROPERTY)), buildLikeValue(filter.getSuite())); } return result; }
@SuppressWarnings({ "rawtypes", "unchecked" }) public Predicate toPredicate(Root<?> root, CriteriaQuery<?> query, CriteriaBuilder builder) { Path expression = null; if(fieldName.contains(".")){ String[] names = StringUtils.split(fieldName, "."); expression = root.get(names[0]); for (int i = 1; i < names.length; i++) { expression = expression.get(names[i]); } }else{ expression = root.get(fieldName); } switch (operator) { case EQ: return builder.equal(expression, value); case NE: return builder.notEqual(expression, value); case LIKE: return builder.like((Expression<String>) expression, "%" + value + "%"); case LT: return builder.lessThan(expression, (Comparable) value); case GT: return builder.greaterThan(expression, (Comparable) value); case LTE: return builder.lessThanOrEqualTo(expression, (Comparable) value); case GTE: return builder.greaterThanOrEqualTo(expression, (Comparable) value); default: return null; } }
private static void _criteria(DbService dbService) { final EntityManager em = dbService.getEntityManager(); // INSERT new record em.getTransaction().begin(); em.persist(new Account("A")); em.persist(new Account("B")); em.persist(new Account("C")); em.getTransaction().commit(); CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<Account> query = builder.createQuery(Account.class); Root<Account> acc = query.from(Account.class); Predicate cond = builder.gt(acc.get("id"), 1); query.where(cond); TypedQuery<Account> q = em.createQuery(query); List<Account> resultList = q.getResultList(); System.out.println(resultList); }
public static Specification<Post> filterByKeywordAndStatus( final String keyword,// final Post.Status status) { return (Root<Post> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> { List<Predicate> predicates = new ArrayList<>(); if (StringUtils.hasText(keyword)) { predicates.add( cb.or( cb.like(root.get(Post_.title), "%" + keyword + "%"), cb.like(root.get(Post_.content), "%" + keyword + "%") ) ); } if (status != null) { predicates.add(cb.equal(root.get(Post_.status), status)); } return cb.and(predicates.toArray(new Predicate[predicates.size()])); }; }
@Override public Page search(QueryCriteria criteria, Pageable pageable) { CriteriaBuilder builder = this.entityManager.getCriteriaBuilder(); CriteriaQuery<Long> countCriteria = builder.createQuery(Long.class); Root<T> countRoot = countCriteria.from(this.domainClass); long total = this.entityManager.createQuery( countCriteria.select(builder.count(countRoot)) .where(toPredicates(criteria, countRoot, builder)) ).getSingleResult(); CriteriaQuery<T> pageCriteria = builder.createQuery(this.domainClass); Root<T> pageRoot = pageCriteria.from(this.domainClass); List<T> list = this.entityManager.createQuery( pageCriteria.select(pageRoot) .where(toPredicates(criteria, pageRoot, builder)) .orderBy(toOrders(pageable.getSort(), pageRoot, builder)) ).setFirstResult(pageable.getOffset()) .setMaxResults(pageable.getPageSize()) .getResultList(); return new PageImpl<>(new ArrayList<>(list), pageable, total); }
/** * retrieves the <code>RolesPermission</code> by the role. * * @param role * the role * @return userPermissions the list of permissions of the user * */ public static Set<String> getPermission(String role) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("userData"); EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); tx.begin(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<RolePermission> q = cb.createQuery(RolePermission.class); Root<RolePermission> c = q.from(RolePermission.class); q.select(c).where(cb.equal(c.get("roleName"), role)); TypedQuery<RolePermission> query = em.createQuery(q); List<RolePermission> permissions = query.getResultList(); Set<String> userPermissions = new HashSet<String>(); for (RolePermission permission : permissions) userPermissions.add(permission.getPermission()); tx.commit(); em.close(); return userPermissions; }
public static Pod findExternalId(EntityManager em, String externalId) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Pod> query = cb.createQuery(Pod.class); Root<Pod> root = query.from(Pod.class); query = query.select(root) .where(cb.equal(root.get("externalId"), externalId)); try { return em.createQuery(query).getSingleResult(); } catch (NoResultException nre) { return null; } }
@GET @Produces({"application/xml", "application/json"}) @Path("/recent/producttype/{id}/{orderLineId}") public List<LiveSalesList> findRecentProductTypeFrom(@PathParam("id") Integer productTypeId, @PathParam("orderLineId") Integer orderLineId) { CriteriaBuilder cb = getEntityManager().getCriteriaBuilder(); javax.persistence.criteria.CriteriaQuery cq = cb.createQuery(); Root<LiveSalesList> liveSalesList = cq.from(LiveSalesList.class); cq.select(liveSalesList); cq.where(cb.and( cb.equal(liveSalesList.get(LiveSalesList_.productTypeId), productTypeId), cb.gt(liveSalesList.get(LiveSalesList_.orderLineId), orderLineId) )); Query q = getEntityManager().createQuery(cq); q.setMaxResults(500); return q.getResultList(); }
@GET @Produces({"application/xml", "application/json"}) @Path("/recent/region/producttype/{regionName}/{productTypeId}") public List<LiveSalesList> findRecentRegionProductType(@PathParam("regionName") String regionName, @PathParam("productTypeId") Integer productTypeId) { CriteriaBuilder cb = getEntityManager().getCriteriaBuilder(); javax.persistence.criteria.CriteriaQuery cq = cb.createQuery(); Root<LiveSalesList> liveSalesList = cq.from(LiveSalesList.class); cq.select(liveSalesList); cq.where(cb.and( cb.equal(liveSalesList.get(LiveSalesList_.productTypeId), productTypeId), cb.equal(liveSalesList.get(LiveSalesList_.region), regionName) )); Query q = getEntityManager().createQuery(cq); q.setMaxResults(500); return q.getResultList(); }
@Override public Predicate toPredicate(Root<Object> root, CriteriaQuery<?> cq, CriteriaBuilder cb) { List<Predicate> predicates = new ArrayList<>(); for(Specification specification: specifications){ Predicate p = specification.toPredicate(root, cq, cb); if(p!=null) predicates.add(p); } return cb.and(predicates.toArray(new Predicate[predicates.size()])); }
public List<ClanEntity> search(String name, int minMembers, int maxMembers, int minTrophies, boolean onlyJoinable) { try (Session session = session()) { CriteriaBuilder builder = session.getCriteriaBuilder(); CriteriaQuery<ClanEntity> query = builder.createQuery(ClanEntity.class); Root<ClanEntity> root = query.from(ClanEntity.class); query.select(root); if (name != null && !name.isEmpty()) { query.where(builder.like(root.get("name"), "%" + name + "%")); } // TODO: Check min and max members if (minTrophies != 0) { query.where(builder.greaterThan(root.get("score"), minTrophies)); } if (onlyJoinable) { query.where(builder.equal(root.get("type"), builder.literal(ClanType.OPEN))); // TODO: Check members } return session.createQuery(query).getResultList(); } }
public static Appliance findByModel(EntityManager em, String model) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Appliance> query = cb.createQuery(Appliance.class); Root<Appliance> root = query.from(Appliance.class); query = query.select(root) .where(cb.equal(root.get("model"), model)); try { return em.createQuery(query).getSingleResult(); } catch (NoResultException nre) { return null; } }
public Pessoa validarUsuario(String log, String pass){ final CriteriaBuilder cb = getEntityManager().getCriteriaBuilder(); final CriteriaQuery<Pessoa> cquery = cb.createQuery(Pessoa.class); final Root<Pessoa> root = cquery.from(Pessoa.class); final List<Predicate> condicoes = new ArrayList<Predicate>(); condicoes.add(cb.equal(root.get("usuario").get("login"), log)); condicoes.add(cb.equal(root.get("usuario").get("senha"), pass)); cquery.select(root).where(condicoes.toArray(new Predicate[]{})); Pessoa pessoa = new Pessoa(); try{ pessoa = getEntityManager().createQuery(cquery).getSingleResult(); } catch (Exception e) { throw new QueryTimeoutException("Usuário ou senha invalido!"); } return pessoa; }
@Override public Community findByName(String name) { LOG.info("findByName(name = " + name + ")"); CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<Community> criteria = builder.createQuery(Community.class); Root<Community> community = criteria.from(Community.class); criteria.where(builder.equal(community.get("name"), name)); TypedQuery<Community> query = em.createQuery(criteria); try { Community c = query.getSingleResult(); return initializeCom(c); } catch (NoResultException e) { LOG.error(e.toString()); return null; } }
public static boolean isControllerTypeUsed(String controllerType, EntityManager em) { Long count = 0L; try { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Long> query = cb.createQuery(Long.class); Root<VirtualizationConnector> root = query.from(VirtualizationConnector.class); query = query.select(cb.count(root)) .where(cb.equal(root.get("controllerType"), controllerType)); count = em.createQuery(query).getSingleResult(); } catch (Exception e) { // Ignore this exception } return count > 0; }
/** * Apply ordering criteria. */ private <T> void applyOrder(final UiPageRequest uiPageRequest, final Map<String, String> mapping, final CriteriaBuilder builder, final CriteriaQuery<T> query, final Root<T> root) { // Apply the sort if (uiPageRequest.getUiSort() != null) { // Need to order the result final UiSort uiSort = uiPageRequest.getUiSort(); final String ormColumn = mapping.get(uiSort.getColumn()); if (ormColumn != null) { // ORM column is validated final Sort sort = new Sort(uiSort.getDirection(), mapping.get(uiSort.getColumn())); query.orderBy(QueryUtils.toOrders(sort, root, builder)); } } }
/** * All customers with an {@link Account} expiring before the given date. * * @param date * @return */ public static Specification<Customer> accountExpiresBefore(final LocalDate date) { return new Specification<Customer>() { @Override public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) { Root<Account> accounts = query.from(Account.class); Path<Date> expiryDate = accounts.<Date> get("expiryDate"); Predicate customerIsAccountOwner = cb.equal(accounts.<Customer> get("customer"), root); Predicate accountExpiryDateBefore = cb.lessThan(expiryDate, date.toDateTimeAtStartOfDay().toDate()); return cb.and(customerIsAccountOwner, accountExpiryDateBefore); } }; }
@Override public PolicyEntity getPolicy(String policyId, String domainId) throws Exception { return this.txControl.supports(new Callable<PolicyEntity>() { @Override public PolicyEntity call() throws Exception { CriteriaBuilder criteriaBuilder = IsmPolicyApi.this.em.getCriteriaBuilder(); CriteriaQuery<PolicyEntity> query = criteriaBuilder.createQuery(PolicyEntity.class); Root<PolicyEntity> r = query.from(PolicyEntity.class); query.select(r) .where(criteriaBuilder.and( criteriaBuilder.equal(r.get("domain").get("id"), Long.parseLong(domainId)), criteriaBuilder.equal(r.get("id"), Long.parseLong(policyId)))); List<PolicyEntity> result = IsmPolicyApi.this.em.createQuery(query).getResultList(); if (result.isEmpty()) { throw new Exception("Policy or Domain Entity does not exists..."); //TODO - Add 404 error response - Sudhir } return result.get(0); } }); }
@Override public List<Community> findApprovedCommunities() { LOG.info("findApprovedCommunites()"); CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<Community> criteria = builder.createQuery(Community.class); Root<Community> community = criteria.from(Community.class); try { criteria.where(builder.equal(community.get("state"), new Enumeration(2))); } catch (DatabaseException e1) { LOG.error("Enumeration(2).APPROVED konnte nicht erstellt werden!"); } TypedQuery<Community> query = em.createQuery(criteria); try { List <Community> coms = query.getResultList(); for(Community c : coms) { initializeCom(c); } return coms; } catch (NoResultException e) { LOG.error(e.toString()); return null; } }
@Override public ManagerSecurityGroupElement getSecurityGroupById(String mgrSecurityGroupId) throws Exception { if (mgrSecurityGroupId == null) { return null; } DeviceEntity device = this.validationUtil.getDeviceOrThrow(this.vs.getMgrId()); return this.txControl.supports(() -> { CriteriaBuilder cb = IsmSecurityGroupApi.this.em.getCriteriaBuilder(); CriteriaQuery<SecurityGroupEntity> query = cb.createQuery(SecurityGroupEntity.class); Root<SecurityGroupEntity> root = query.from(SecurityGroupEntity.class); query.select(root).where(cb.equal(root.get("id"), Long.valueOf(mgrSecurityGroupId)), cb.equal(root.get("device"), device)); SecurityGroupEntity result = null; try { result = IsmSecurityGroupApi.this.em.createQuery(query).getSingleResult(); } catch (NoResultException e) { LOG.error(String.format("Cannot find Security group with id %s under device %s", mgrSecurityGroupId, device.getId())); } return result; }); }
public User findUser(String p_username) { CriteriaBuilder builder = em().getCriteriaBuilder(); CriteriaQuery<User> criteria = builder.createQuery(User.class ); Root<User> user_root = criteria.from(User.class); criteria.select(user_root); criteria.where(builder.equal(user_root.get("userName"), p_username)); try { User u = em().createQuery(criteria).getSingleResult(); return u; } catch (NoResultException ex) { return null; } }
@Override public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) { Predicate resultPredicate = null; List<Predicate> predicates = buildPredicates(root, cb); if (!predicates.isEmpty()) { resultPredicate = cb.and(predicates.toArray(new Predicate[predicates.size()])); } return resultPredicate; }
private Predicate buildRangePredicate(Range<T> range, Root<T> root, CriteriaBuilder builder) { if (range.isBetween()) { return builder.between(root.get(range.getField()), range.getFrom(), range.getTo()); } else if (range.isFromSet()) { return builder.greaterThanOrEqualTo(root.get(range.getField()), range.getFrom()); } else if (range.isToSet()) { return builder.lessThanOrEqualTo(root.get(range.getField()), range.getTo()); } return null; }
public static List<SecurityGroup> listOtherSecurityGroupsWithSameNetworkElementID(EntityManager em, SecurityGroup sg) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<SecurityGroup> query = cb.createQuery(SecurityGroup.class); Root<SecurityGroup> root = query.from(SecurityGroup.class); query = query.select(root).where(cb.equal(root.get("networkElementId"), sg.getNetworkElementId()), cb.equal(root.get("projectId"), sg.getProjectId()), cb.notEqual(root, sg)); List<SecurityGroup> list = em.createQuery(query).getResultList(); return list; }
private List<Predicate> buildPredicates(Root<User> root, CriteriaBuilder cb) { List<Predicate> predicates = new ArrayList<>(); conditions.forEach((k, v) -> { if (Optional.ofNullable(v).isPresent()) { predicates.add(cb.like(root.get(k), "%" + String.valueOf(v.toString()) + "%")); } }); return predicates; }
private long countDefault(final Specification<T> specification, final DatatableQuery<?, T> input) { final EntityManager entityManager = entityManagerFactory.createEntityManager(); final CriteriaBuilder qb = entityManager.getCriteriaBuilder(); final CriteriaQuery<Long> cq = qb.createQuery(Long.class); final Root<T> from = cq.from(this.entity); cq.select(qb.count(from)); if (specification != null) { cq.where(specification.toPredicate(from, cq, qb)); } final long ret = entityManager.createQuery(cq).getSingleResult(); entityManager.close(); return ret; }
public UserDataSet readByName(String name) { CriteriaBuilder builder = session.getCriteriaBuilder(); CriteriaQuery<UserDataSet> criteria = builder.createQuery(UserDataSet.class); Root<UserDataSet> from = criteria.from(UserDataSet.class); criteria.where(builder.equal(from.get("name"), name)); Query<UserDataSet> query = session.createQuery(criteria); return query.uniqueResult(); }
public List<ToDoList> rechercherToDoList() { //Fonction hibernate pour construire les requêtes. final CriteriaBuilder lCriteriaBuilder = entityManager.getCriteriaBuilder(); //Creation de la requête de select final CriteriaQuery<ToDoList> lCriteriaQuery = lCriteriaBuilder.createQuery(ToDoList.class); final Root<ToDoList> lRoot = lCriteriaQuery.from(ToDoList.class); lCriteriaQuery.select(lRoot); final TypedQuery<ToDoList> lTypedQuery = entityManager.createQuery(lCriteriaQuery); return lTypedQuery.getResultList(); }
public static List<SecurityGroup> listByProtectAllAndProjectId(EntityManager em, String projectId) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<SecurityGroup> query = cb.createQuery(SecurityGroup.class); Root<SecurityGroup> root = query.from(SecurityGroup.class); query = query.select(root) .distinct(true) .where(cb.and( cb.equal(root.get("projectId"), projectId), cb.equal(root.get("protectAll"), true))); return em.createQuery(query).getResultList(); }
public static boolean isManagerTypeUsed(String managerType, EntityManager em) { try { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Long> cq; Root<?> from; cq = cb.createQuery(Long.class); from = cq.from(ApplianceManagerConnector.class); cq = cq.select(cb.count(from)) .where(cb.equal(from.get("managerType"), managerType)); Long count1 = em.createQuery(cq).getSingleResult(); cq = cb.createQuery(Long.class); from = cq.from(Appliance.class); cq = cq.select(cb.count(from)) .where(cb.equal(from.get("managerType"), managerType)); Long count2 = em.createQuery(cq).getSingleResult(); return count1 > 0 || count2 > 0; } catch (Exception e) { return true; } }
public Collection<ExtGraph> findByWordAndPackageNo(String word, int packageno) { Long pkg = new Long(packageno); CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder(); CriteriaQuery<ExtGraph> criteriaQuery = criteriaBuilder.createQuery(ExtGraph.class ); Root<ExtGraph> root = criteriaQuery.from(ExtGraph.class); Join<ExtGraph, Synset> synset = root.join("synset", JoinType.INNER); Join<Synset, Sense> sts = synset.join("sense", JoinType.LEFT); List<Predicate> criteriaList = new ArrayList<>(); Predicate firstCondition = criteriaBuilder.equal(root.get("word"), word); criteriaList.add(firstCondition); Predicate secondCondition = criteriaBuilder.equal(root.get("packageno"), pkg); criteriaList.add(secondCondition); Predicate thirdCondition = criteriaBuilder.equal(sts.get("senseIndex"), 0); criteriaList.add(thirdCondition); criteriaQuery.where(criteriaBuilder.and(criteriaList.toArray(new Predicate[0]))); final TypedQuery<ExtGraph> query = getEntityManager().createQuery(criteriaQuery); return query.getResultList(); }
@Override public List<NodeResult> list(BigInteger jobId) { return execute(session -> { CriteriaBuilder builder = session.getCriteriaBuilder(); CriteriaQuery<NodeResult> select = builder.createQuery(NodeResult.class); Root<NodeResult> nodeResultRoot = select.from(NodeResult.class); Predicate aCondition = builder.equal(nodeResultRoot.get("key").get("jobId"), jobId); select.where(aCondition); select.orderBy(builder.asc(nodeResultRoot.get("order"))); return session.createQuery(select).list(); }); }
public List<TaskRecord> getUncompletedTasks() { CriteriaBuilder cb = this.em.getCriteriaBuilder(); CriteriaQuery<TaskRecord> query = cb.createQuery(TaskRecord.class); Root<TaskRecord> from = query.from(TaskRecord.class); query = query.select(from).where( cb.notEqual(from.get("state"), COMPLETED)); return this.em.createQuery(query).getResultList(); }
/** * Creates a new count query for the given {@link Specification}. */ private <T> TypedQuery<Long> getCountQuery(final Class<T> entityType, final Specification<T> spec) { final CriteriaBuilder builder = em.getCriteriaBuilder(); final CriteriaQuery<Long> query = builder.createQuery(Long.class); final Root<T> root = query.from(entityType); applySpecificationToCriteria(root, spec, query); query.select(builder.count(root)); return em.createQuery(query); }
public static List<SecurityGroup> listOtherSecurityGroupsWithSameSFC(EntityManager em, SecurityGroup sg) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<SecurityGroup> query = cb.createQuery(SecurityGroup.class); Root<SecurityGroup> root = query.from(SecurityGroup.class); query = query.select(root).where(cb.equal(root.join("serviceFunctionChain"), sg.getServiceFunctionChain()), cb.equal(root.get("projectId"), sg.getProjectId()), cb.notEqual(root, sg), cb.isNotNull(root.get("networkElementId"))); List<SecurityGroup> list = em.createQuery(query).getResultList(); return list; }
protected static Predicate and(CriteriaBuilder criteriaBuilder, Predicate... predicate) { Predicate result = null; for (int i = 0; i < predicate.length; i++) { if (predicate[i] != null) { if (result == null) { result = predicate[i]; } else { result = criteriaBuilder.and(result, predicate[i]); } } } return result; }
@Override public Predicate toPredicate(Root<?> root, CriteriaQuery<?> query, CriteriaBuilder builder) { List<Predicate> predicates = new ArrayList<Predicate>(); for (int i = 0; i < this.criterion.length; i++) { predicates.add(this.criterion[i].toPredicate(root, query, builder)); } switch (operator) { case OR: return builder.or(predicates.toArray(new Predicate[predicates.size()])); default: return null; } }