Example usage for javax.persistence.criteria Path get

List of usage examples for javax.persistence.criteria Path get

Introduction

In this page you can find the example usage for javax.persistence.criteria Path get.

Prototype

<Y> Path<Y> get(String attributeName);

Source Link

Document

Create a path corresponding to the referenced attribute.

Usage

From source file:com.fantasy.stataggregator.workers.StatCompilerTask.java

@Override
public void setYear(int year) throws Exception {
    this.year = year;

    GameDataRepository gdr = ctx.getBean(GameDataRepository.class);
    if (year == Integer.MAX_VALUE) {
        gamesData = gdr.findAll();/*from   w  w w  . j  a  v a  2  s .c  o  m*/
    } else {
        SimpleDateFormat sdf = ctx.getBean(SimpleDateFormat.class);
        sdf.applyLocalizedPattern("yyyyMMdd");

        Date min = sdf.parse(year + START_OF_YEAR);
        Date max = sdf.parse(year + END_OF_YEAR);

        CriteriaBuilder cb = gdr.getCriteriaBuilder();
        CriteriaQuery<GameData> cq = gdr.getCriteriaQuery();
        Root<GameData> gameData = gdr.getRoot();
        Path<GameDataPK> pk = gameData.get(GameData_.gameDataPK);
        cq.select(gameData).where(cb.equal(pk.get(GameDataPK_.year), year))
                .orderBy(cb.asc(pk.get(GameDataPK_.gameIdentifier)));

        gamesData = gdr.getCriteriaList(cq);
        System.out.println(gamesData.size());
    }
}

From source file:net.kaczmarzyk.spring.data.jpa.domain.PathSpecification.java

@SuppressWarnings("unchecked")
protected <F> Path<F> path(Root<T> root) {
    Path<?> expr = null;
    for (String field : path.split("\\.")) {
        if (expr == null) {
            expr = root.get(field);//from  ww  w . j  av  a  2  s .  c  om
        } else {
            expr = expr.get(field);
        }
    }
    return (Path<F>) expr;
}

From source file:me.ineson.demo.service.utils.RestUtils.java

/**
 * @param where//from ww  w  .  j  a  v  a  2 s  .  co  m
 * @param root
 * @param query
 * @param builder
 * @param translations
 * @return
 */
public static Predicate parseWhereClause(String where, Root<?> root, CriteriaQuery<?> query,
        CriteriaBuilder builder, Map<String, String> translations) {

    List<Predicate> predicates = new ArrayList<Predicate>();
    for (String singleCriteria : new StrTokenizer(where, ",").getTokenList()) {
        if (StringUtils.isNotBlank(singleCriteria)) {
            int equalsIndex = singleCriteria.indexOf("=");
            if (equalsIndex > 0) {
                String fieldPath = singleCriteria.substring(0, equalsIndex);
                String value = singleCriteria.substring(equalsIndex + 1);

                if (translations != null && translations.containsKey(fieldPath)) {
                    String newFieldPath = translations.get(fieldPath);
                    log.debug("replacing field {} with {} ", fieldPath, newFieldPath);
                    fieldPath = newFieldPath;
                }

                StrTokenizer tokenizer = new StrTokenizer(fieldPath, ".");

                javax.persistence.criteria.Path<?> expression = null;
                while (tokenizer.hasNext()) {
                    String field = tokenizer.next();
                    if (tokenizer.hasNext()) {
                        if (expression == null) {
                            expression = root.join(field);
                        } else {
                            // expression = expression.join( field);
                            throw new IllegalArgumentException(
                                    "Paths to joins of greater than a depth of 1 are not implemented yet");
                        }
                    } else {
                        if (expression == null) {
                            log.info("expression0 {}", expression);
                            expression = root.get(field);
                            log.info("expression1 {}", expression);
                        } else {
                            expression = expression.get(field);
                        }
                    }
                }

                Object realValue = value;
                if ("bodyType".equals(fieldPath)) {
                    me.ineson.demo.service.SolarBodyType solarBodyType = me.ineson.demo.service.SolarBodyType
                            .valueOf(value);
                    switch (solarBodyType) {
                    case PLANET:
                        realValue = SolarBodyType.Planet;
                        break;

                    case SUN:
                        realValue = SolarBodyType.Sun;
                        break;

                    case DWARF_PLANET:
                        realValue = SolarBodyType.DwarfPlanet;
                        break;

                    default:
                        realValue = solarBodyType;
                    }
                    log.info("enum bodyType before {} after {}", value, realValue);
                }

                log.info("expression9 {}", expression);
                predicates.add(builder.equal(expression, realValue));
            }

        }
    }

    log.debug("predictes ");
    if (predicates.size() == 0) {
        return null;
    }
    if (predicates.size() == 1) {
        return predicates.get(0);
    }
    return builder.and(predicates.toArray(new Predicate[predicates.size()]));
}

From source file:com.dbs.sdwt.jpa.ByPropertySelectorUtil.java

private <E> void byObjectAndModeSelector(Root<E> root, CriteriaBuilder builder, List<Predicate> predicates,
        SearchParameters sp, PropertySelector<? super E, ?> selector) {
    List<Predicate> selectorPredicates = newArrayList();
    List<?> selected = selector.getSelected();
    if (selected.contains(null)) {
        selected = newArrayList(selector.getSelected());
        selected.remove(null);//w ww  .  ja  v a 2 s .c  o  m
        selectorPredicates.add(builder.isNull(jpaUtil.getPath(root, selector.getAttributes())));
    }
    for (Object selection : selected) {
        Path<?> path = jpaUtil.getPath(root, selector.getAttributes());
        if (selection instanceof Identifiable) {
            selectorPredicates.add(builder.equal(path.get("id"), ((Identifiable<?>) selection).getId()));
        } else {
            selectorPredicates.add(builder.equal(path, selection));
        }
    }
    predicates.add(jpaUtil.andPredicate(builder, selectorPredicates));
}

From source file:com.ims.service.ProductStockInfoService.java

public List<ProductStockInfo> findProdStockInfoListFrom(final ProdStockSearchCriteria stockSearchCriteria) {
    Specification<ProductStockInfo> speci = new Specification<ProductStockInfo>() {
        @Override// w  w w . jav a2 s.co  m
        public Predicate toPredicate(Root<ProductStockInfo> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            List<Predicate> predicates = new ArrayList<Predicate>();
            predicates.add(cb.equal(root.get("stockType"), stockSearchCriteria.getStockType()));
            if (StringUtils.isNotEmpty(stockSearchCriteria.getProdCategoryCode())) {
                predicates.add(cb.equal(root.get("categoryCode"), stockSearchCriteria.getProdCategoryCode()));
            }
            if (StringUtils.isNotEmpty(stockSearchCriteria.getProdCode())) {
                predicates.add(cb.like(root.<String>get("productCode"),
                        "%" + stockSearchCriteria.getProdCode() + "%"));
            }
            String compareCode = stockSearchCriteria.getCompareCode();
            if (StringUtils.isNotEmpty(compareCode) && stockSearchCriteria.isIncludeComparedValue()) {
                Path<ProductAmount> productAmount = root.<ProductAmount>get("productAmount");
                if (CompareCode.isEqual(compareCode)) {
                    predicates.add(
                            cb.equal(productAmount.get("totalAmount"), stockSearchCriteria.getStockAmount()));
                } else if (CompareCode.isGreater(compareCode)) {
                    predicates.add(cb.greaterThan(productAmount.<Integer>get("totalAmount"),
                            stockSearchCriteria.getStockAmount()));
                } else if (CompareCode.isLess(compareCode)) {
                    predicates.add(cb.lessThan(productAmount.<Integer>get("totalAmount"),
                            stockSearchCriteria.getStockAmount()));
                } else if (CompareCode.isGreaterOrEqual(compareCode)) {
                    predicates.add(cb.greaterThanOrEqualTo(productAmount.<Integer>get("totalAmount"),
                            stockSearchCriteria.getStockAmount()));
                } else if (CompareCode.isLessOrEqual(compareCode)) {
                    predicates.add(cb.lessThanOrEqualTo(productAmount.<Integer>get("totalAmount"),
                            stockSearchCriteria.getStockAmount()));
                } else if (CompareCode.isEqualAlertAmount(compareCode)) {
                    predicates.add(cb.equal(productAmount.get("totalAmount"), root.get("alertStockAmount")));
                } else if (CompareCode.isGreaterThanAlertAmount(compareCode)) {
                    predicates.add(cb.greaterThan(productAmount.<String>get("totalAmount"),
                            root.<String>get("alertStockAmount")));
                } else if (CompareCode.isLessThanAlertAmount(compareCode)) {
                    predicates.add(cb.lessThan(productAmount.<String>get("totalAmount"),
                            root.<String>get("alertStockAmount")));
                }

                if (stockSearchCriteria.isTransformAction()
                        && ((CompareCode.isLess(compareCode) || CompareCode.isLessOrEqual(compareCode)))) {
                    predicates.add(cb.greaterThan(productAmount.<Integer>get("totalAmount"), 0));
                }
            }

            query.where(cb.and(predicates.toArray(new Predicate[predicates.size()])))
                    .orderBy(cb.desc(root.get("categoryCode")), cb.asc(root.get("productCode")));
            return null;
        }
    };

    return productStockInfoRepository.findAll(speci);
}

From source file:dk.dma.msinm.service.CategoryService.java

/**
 * Looks up an category by name/*from   w w  w .  j  a v  a2 s .c  o  m*/
 * @param name the name to search for
 * @param lang the language. Optional
 * @param parentId the parent ID. Optional
 * @return The matching category, or null if not found
 */
public Category findByName(String name, String lang, Integer parentId) {
    // Sanity check
    if (StringUtils.isBlank(name)) {
        return null;
    }

    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Category> categoryQuery = builder.createQuery(Category.class);

    Root<Category> categoryRoot = categoryQuery.from(Category.class);

    // Build the predicate
    PredicateHelper<Category> predicateBuilder = new PredicateHelper<>(builder, categoryQuery);

    // Match the name
    Join<Category, CategoryDesc> descs = categoryRoot.join("descs", JoinType.LEFT);
    predicateBuilder.like(descs.get("name"), name);
    // Optionally, match the language
    if (StringUtils.isNotBlank(lang)) {
        predicateBuilder.equals(descs.get("lang"), lang);
    }

    // Optionally, match the parent
    if (parentId != null) {
        categoryRoot.join("parent", JoinType.LEFT);
        Path<Category> parent = categoryRoot.get("parent");
        predicateBuilder.equals(parent.get("id"), parentId);
    }

    // Complete the query
    categoryQuery.select(categoryRoot).distinct(true).where(predicateBuilder.where());

    // Execute the query and update the search result
    List<Category> result = em.createQuery(categoryQuery).getResultList();

    return result.size() > 0 ? result.get(0) : null;
}

From source file:com.dbs.sdwt.jpa.ByExampleUtil.java

@SuppressWarnings("unchecked")
public <T extends Identifiable<?>, M2O extends Identifiable<?>> List<Predicate> byExampleOnXToOne(
        ManagedType<T> mt, Root<T> mtPath, T mtValue, SearchParameters sp, CriteriaBuilder builder) {
    List<Predicate> predicates = newArrayList();
    for (SingularAttribute<? super T, ?> attr : mt.getSingularAttributes()) {
        if (attr.getPersistentAttributeType() == MANY_TO_ONE
                || attr.getPersistentAttributeType() == ONE_TO_ONE) {
            M2O m2oValue = (M2O) jpaUtil.getValue(mtValue, mt.getAttribute(attr.getName()));
            Class<M2O> m2oType = (Class<M2O>) attr.getBindableJavaType();
            Path<M2O> m2oPath = (Path<M2O>) mtPath.get(attr);
            ManagedType<M2O> m2oMt = em.getMetamodel().entity(m2oType);
            if (m2oValue != null) {
                if (m2oValue.isIdSet()) { // we have an id, let's restrict only on this field
                    predicates.add(builder.equal(m2oPath.get("id"), m2oValue.getId()));
                } else {
                    predicates.addAll(byExample(m2oMt, m2oPath, m2oValue, sp, builder));
                }/*from   ww w  . j  av a 2s.c  o  m*/
            }
        }
    }
    return predicates;
}

From source file:dk.dma.msinm.service.AreaService.java

/**
 * Looks up an area by name//w w w  .ja  v  a 2 s  . c o m
 * @param name the name to search for
 * @param lang the language. Optional
 * @param parentId the parent ID. Optional
 * @return The matching area, or null if not found
 */
public Area findByName(String name, String lang, Integer parentId) {
    // Sanity check
    if (StringUtils.isBlank(name)) {
        return null;
    }

    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Area> areaQuery = builder.createQuery(Area.class);

    Root<Area> areaRoot = areaQuery.from(Area.class);

    // Build the predicate
    PredicateHelper<Area> predicateBuilder = new PredicateHelper<>(builder, areaQuery);

    // Match the name
    Join<Area, AreaDesc> descs = areaRoot.join("descs", JoinType.LEFT);
    predicateBuilder.like(descs.get("name"), name);
    // Optionally, match the language
    if (StringUtils.isNotBlank(lang)) {
        predicateBuilder.equals(descs.get("lang"), lang);
    }

    // Optionally, match the parent
    if (parentId != null) {
        areaRoot.join("parent", JoinType.LEFT);
        Path<Area> parent = areaRoot.get("parent");
        predicateBuilder.equals(parent.get("id"), parentId);
    }

    // Complete the query
    areaQuery.select(areaRoot).distinct(true).where(predicateBuilder.where());

    // Execute the query and update the search result
    List<Area> result = em.createQuery(areaQuery).getResultList();

    return result.size() > 0 ? result.get(0) : null;
}

From source file:net.shopxx.dao.impl.CouponCodeDaoImpl.java

public Long count(Coupon coupon, Member member, Boolean hasBegun, Boolean hasExpired, Boolean isUsed) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<CouponCode> criteriaQuery = criteriaBuilder.createQuery(CouponCode.class);
    Root<CouponCode> root = criteriaQuery.from(CouponCode.class);
    criteriaQuery.select(root);/*from w ww . j a v  a  2 s . co m*/
    Predicate restrictions = criteriaBuilder.conjunction();
    Path<Coupon> couponPath = root.get("coupon");
    if (coupon != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(couponPath, coupon));
    }
    if (member != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("member"), member));
    }
    if (hasBegun != null) {
        if (hasBegun) {
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.or(couponPath.get("beginDate").isNull(),
                            criteriaBuilder.lessThanOrEqualTo(couponPath.<Date>get("beginDate"), new Date())));
        } else {
            restrictions = criteriaBuilder.and(restrictions, couponPath.get("beginDate").isNotNull(),
                    criteriaBuilder.greaterThan(couponPath.<Date>get("beginDate"), new Date()));
        }
    }
    if (hasExpired != null) {
        if (hasExpired) {
            restrictions = criteriaBuilder.and(restrictions, couponPath.get("endDate").isNotNull(),
                    criteriaBuilder.lessThanOrEqualTo(couponPath.<Date>get("endDate"), new Date()));
        } else {
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.or(couponPath.get("endDate").isNull(),
                            criteriaBuilder.greaterThan(couponPath.<Date>get("endDate"), new Date())));
        }
    }
    if (isUsed != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isUsed"), isUsed));
    }
    criteriaQuery.where(restrictions);
    return super.count(criteriaQuery, null);
}