Example usage for javax.persistence.criteria Root join

List of usage examples for javax.persistence.criteria Root join

Introduction

In this page you can find the example usage for javax.persistence.criteria Root join.

Prototype

<Y> Join<X, Y> join(SingularAttribute<? super X, Y> attribute, JoinType jt);

Source Link

Document

Create a join to the specified single-valued attribute using the given join type.

Usage

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

/**
 * Looks up an category by name//  w  ww .  ja v  a 2s .co  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:org.oncoblocks.centromere.jpa.test.JpaRepositoryTests.java

@Test
public void joinTest() throws Exception {
    Specification<EntrezGene> specification = new Specification<EntrezGene>() {
        @Override//from www.j ava  2 s  . c o m
        public Predicate toPredicate(Root<EntrezGene> root, CriteriaQuery<?> criteriaQuery,
                CriteriaBuilder criteriaBuilder) {
            root.join("aliases", JoinType.LEFT);
            return criteriaBuilder.equal(root.get("aliases.name"), "ABC");
        }
    };
}

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

/**
 * Looks up an area by name//from 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:com.deloitte.smt.service.SignalDetectionService.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public SmtResponse findAllForSearch(SearchDto searchDto) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery criteriaQuery = criteriaBuilder.createQuery();

    Root<SignalDetection> rootSignalDetection = criteriaQuery.from(SignalDetection.class);
    Join<SignalDetection, TopicSignalDetectionAssignmentAssignees> joinDetectionAssignees = rootSignalDetection
            .join("topicSignalDetectionAssignmentAssignees", JoinType.LEFT); //left outer join

    if (null != searchDto) {
        Root<Ingredient> rootIngredient = criteriaQuery.from(Ingredient.class);
        List<Predicate> predicates = new ArrayList<>(10);
        predicates.add(criteriaBuilder.equal(rootSignalDetection.get("id"),
                rootIngredient.get(SmtConstant.DETECTION_ID.getDescription())));

        addDescription(searchDto, criteriaBuilder, rootSignalDetection, predicates);
        addFrequency(searchDto, criteriaBuilder, rootSignalDetection, predicates);
        addIngredients(searchDto, criteriaBuilder, rootIngredient, predicates);
        addProducts(searchDto, criteriaBuilder, criteriaQuery, rootSignalDetection, predicates);
        addLicenses(searchDto, criteriaBuilder, criteriaQuery, rootSignalDetection, predicates);
        addSocs(searchDto, criteriaBuilder, criteriaQuery, rootSignalDetection, predicates);
        addHlts(searchDto, criteriaBuilder, criteriaQuery, rootSignalDetection, predicates);
        addHlgts(searchDto, criteriaBuilder, criteriaQuery, rootSignalDetection, predicates);
        addPts(searchDto, criteriaBuilder, criteriaQuery, rootSignalDetection, predicates);
        addCreatedOrLastRunDate(searchDto, criteriaBuilder, rootSignalDetection, predicates);
        /**TopicSignalValidationAssignmentAssignees **/
        addUserGroupKeys(searchDto, criteriaBuilder, joinDetectionAssignees, rootSignalDetection, predicates);

        Predicate andPredicate = criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        criteriaQuery.multiselect(rootSignalDetection).where(andPredicate)
                .orderBy(criteriaBuilder
                        .desc(rootSignalDetection.get(SmtConstant.CREATED_DATE.getDescription())))
                .distinct(true);/*from   www  .  j  a  v a2 s  . c  om*/

    } else {
        criteriaQuery.multiselect(rootSignalDetection)
                .orderBy(criteriaBuilder
                        .desc(rootSignalDetection.get(SmtConstant.CREATED_DATE.getDescription())))
                .distinct(true);
    }
    SmtResponse smtResponse = new SmtResponse();
    TypedQuery<SignalDetection> q = entityManager.createQuery(criteriaQuery);
    if (!CollectionUtils.isEmpty(q.getResultList())) {
        smtResponse.setTotalRecords(q.getResultList().size());
    }
    if (searchDto != null && searchDto.getFetchSize() != 0) {
        q.setFirstResult(searchDto.getFromRecord());
        q.setMaxResults(searchDto.getFetchSize());
        smtResponse.setFetchSize(searchDto.getFetchSize());
        smtResponse.setFromRecord(searchDto.getFromRecord());
    }
    smtResponse.setResult(q.getResultList());

    if (!CollectionUtils.isEmpty(smtResponse.getResult())) {
        List<SignalDetection> result = (List<SignalDetection>) smtResponse.getResult();
        for (SignalDetection signalDetection : result) {
            signalDetection.setDenominatorForPoisson(
                    denominatorForPoissonRepository.findByDetectionId(signalDetection.getId()));
        }
    }
    return smtResponse;
}

From source file:cn.buk.hotel.dao.HotelDaoImpl.java

@Override
public List<HotelInfo> searchAvailableHotel(HotelSearchCriteria sc) {

    List<HotelInfo> hotelInfos = null;

    try {//from w w  w  .java  2 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:ca.uhn.fhir.jpa.dao.BaseFhirResourceDao.java

private Predicate createCompositeParamPart(CriteriaBuilder builder, Root<ResourceTable> from,
        RuntimeSearchParam left, IQueryParameterType leftValue) {
    Predicate retVal = null;/*from w  w w.j a va  2s  .c om*/
    switch (left.getParamType()) {
    case STRING: {
        From<ResourceIndexedSearchParamString, ResourceIndexedSearchParamString> stringJoin = from
                .join("myParamsString", JoinType.INNER);
        retVal = createPredicateString(leftValue, left.getName(), builder, stringJoin);
        break;
    }
    case TOKEN: {
        From<ResourceIndexedSearchParamToken, ResourceIndexedSearchParamToken> tokenJoin = from
                .join("myParamsToken", JoinType.INNER);
        retVal = createPredicateToken(leftValue, left.getName(), builder, tokenJoin);
        break;
    }
    case DATE: {
        From<ResourceIndexedSearchParamDate, ResourceIndexedSearchParamDate> dateJoin = from
                .join("myParamsDate", JoinType.INNER);
        retVal = createPredicateDate(builder, dateJoin, leftValue);
        break;
    }
    }

    if (retVal == null) {
        throw new InvalidRequestException(
                "Don't know how to handle composite parameter with type of " + left.getParamType());
    }

    return retVal;
}

From source file:ca.uhn.fhir.jpa.dao.BaseFhirResourceDao.java

private void createSort(CriteriaBuilder theBuilder, Root<ResourceTable> theFrom, SortSpec theSort,
        List<Order> theOrders, List<Predicate> thePredicates) {
    if (theSort == null || isBlank(theSort.getParamName())) {
        return;//from  w w  w.j av  a  2 s.  com
    }

    if ("_id".equals(theSort.getParamName())) {
        From<?, ?> forcedIdJoin = theFrom.join("myForcedId", JoinType.LEFT);
        if (theSort.getOrder() == null || theSort.getOrder() == SortOrderEnum.ASC) {
            theOrders.add(theBuilder.asc(forcedIdJoin.get("myForcedId")));
            theOrders.add(theBuilder.asc(theFrom.get("myId")));
        } else {
            theOrders.add(theBuilder.desc(forcedIdJoin.get("myForcedId")));
            theOrders.add(theBuilder.desc(theFrom.get("myId")));
        }

        createSort(theBuilder, theFrom, theSort.getChain(), theOrders, null);
        return;
    }

    RuntimeResourceDefinition resourceDef = getContext().getResourceDefinition(myResourceType);
    RuntimeSearchParam param = resourceDef.getSearchParam(theSort.getParamName());
    if (param == null) {
        throw new InvalidRequestException("Unknown sort parameter '" + theSort.getParamName() + "'");
    }

    String joinAttrName;
    String sortAttrName;

    switch (param.getParamType()) {
    case STRING:
        joinAttrName = "myParamsString";
        sortAttrName = "myValueExact";
        break;
    case DATE:
        joinAttrName = "myParamsDate";
        sortAttrName = "myValueLow";
        break;
    default:
        throw new NotImplementedException("This server does not support _sort specifications of type "
                + param.getParamType() + " - Can't serve _sort=" + theSort.getParamName());
    }

    From<?, ?> stringJoin = theFrom.join(joinAttrName, JoinType.INNER);
    // Predicate p = theBuilder.equal(stringJoin.get("myParamName"), theSort.getParamName());
    // Predicate pn = theBuilder.isNull(stringJoin.get("myParamName"));
    // thePredicates.add(theBuilder.or(p, pn));

    if (theSort.getOrder() == null || theSort.getOrder() == SortOrderEnum.ASC) {
        theOrders.add(theBuilder.asc(stringJoin.get(sortAttrName)));
    } else {
        theOrders.add(theBuilder.desc(stringJoin.get(sortAttrName)));
    }

    createSort(theBuilder, theFrom, theSort.getChain(), theOrders, null);
}

From source file:ca.uhn.fhir.jpa.dao.SearchBuilder.java

private void createPredicateLastUpdatedForResourceLink(CriteriaBuilder builder, Root<ResourceLink> from,
        List<Predicate> predicates) {
    DateRangeParam lastUpdated = myParams.getLastUpdatedAndRemove();
    if (lastUpdated != null) {
        From<BaseResourceIndexedSearchParam, ResourceTable> defJoin = from.join("mySourceResource",
                JoinType.INNER);/*from   www . j  a v  a  2 s.c om*/
        List<Predicate> lastUpdatedPredicates = createLastUpdatedPredicates(lastUpdated, builder, defJoin);
        predicates.addAll(lastUpdatedPredicates);
    }
}

From source file:ca.uhn.fhir.jpa.dao.SearchBuilder.java

private void createPredicateLastUpdatedForIndexedSearchParam(CriteriaBuilder builder,
        Root<? extends BaseResourceIndexedSearchParam> from, List<Predicate> predicates) {
    DateRangeParam lastUpdated = myParams.getLastUpdatedAndRemove();
    if (lastUpdated != null) {
        From<BaseResourceIndexedSearchParam, ResourceTable> defJoin = from.join("myResource", JoinType.INNER);
        List<Predicate> lastUpdatedPredicates = createLastUpdatedPredicates(lastUpdated, builder, defJoin);
        predicates.addAll(lastUpdatedPredicates);
    }//from  w  w w. j a  v a 2s .  c om
}

From source file:ca.uhn.fhir.jpa.dao.SearchBuilder.java

private Predicate createCompositeParamPart(CriteriaBuilder builder, Root<ResourceTable> from,
        RuntimeSearchParam left, IQueryParameterType leftValue) {
    Predicate retVal = null;/*from  ww w  .  j a  va  2  s. c om*/
    switch (left.getParamType()) {
    case STRING: {
        From<ResourceIndexedSearchParamString, ResourceIndexedSearchParamString> stringJoin = from
                .join("myParamsString", JoinType.INNER);
        retVal = createPredicateString(leftValue, left.getName(), builder, stringJoin);
        break;
    }
    case TOKEN: {
        From<ResourceIndexedSearchParamToken, ResourceIndexedSearchParamToken> tokenJoin = from
                .join("myParamsToken", JoinType.INNER);
        retVal = createPredicateToken(leftValue, left.getName(), builder, tokenJoin);
        break;
    }
    case DATE: {
        From<ResourceIndexedSearchParamDate, ResourceIndexedSearchParamDate> dateJoin = from
                .join("myParamsDate", JoinType.INNER);
        retVal = createPredicateDate(builder, dateJoin, leftValue);
        break;
    }
    case QUANTITY: {
        From<ResourceIndexedSearchParamQuantity, ResourceIndexedSearchParamQuantity> dateJoin = from
                .join("myParamsQuantity", JoinType.INNER);
        retVal = createPredicateQuantity(builder, dateJoin, leftValue);
        break;
    }
    }

    if (retVal == null) {
        throw new InvalidRequestException(
                "Don't know how to handle composite parameter with type of " + left.getParamType());
    }

    return retVal;
}