Example usage for javax.persistence.criteria JoinType LEFT

List of usage examples for javax.persistence.criteria JoinType LEFT

Introduction

In this page you can find the example usage for javax.persistence.criteria JoinType LEFT.

Prototype

JoinType LEFT

To view the source code for javax.persistence.criteria JoinType LEFT.

Click Source Link

Document

Left outer join.

Usage

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

/**
 * Looks up an area by name//  w w  w. ja  va  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.yunguchang.data.ApplicationRepository.java

public TBusApplyinfoEntity getApplicationById(String id, PrincipalExt principalExt) {
    applySecurityFilter("applications", principalExt);

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<TBusApplyinfoEntity> cq = cb.createQuery(TBusApplyinfoEntity.class);
    Root<TBusApplyinfoEntity> applyRoot = cq.from(TBusApplyinfoEntity.class);
    applyRoot.fetch(TBusApplyinfoEntity_.passenger, JoinType.LEFT);
    applyRoot.fetch(TBusApplyinfoEntity_.senduser, JoinType.LEFT);
    cq.where(cb.equal(applyRoot.get(TBusApplyinfoEntity_.uuid), id));
    return Iterables.getFirst(em.createQuery(cq).getResultList(), null);
}

From source file:net.sf.companymanager.qbe.SearchParameters.java

/**
 * Returns the attribute (x-to-one association) which must be fetched with a
 * left join.//  w ww  .  j a  va  2  s .com
 * @return List
 */
public List<SingularAttribute<?, ?>> getLeftJoinAttributes() {
    return getJoinAttributes(JoinType.LEFT);
}

From source file:com.yunguchang.data.ApplicationRepository.java

public List<TBusApplyinfoEntity> getApplicationByScheduleId(String scheduleId, PrincipalExt principalExt) {
    applySecurityFilter("applications", principalExt);

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<TBusApplyinfoEntity> cq = cb.createQuery(TBusApplyinfoEntity.class);
    Root<TBusApplyinfoEntity> applyRoot = cq.from(TBusApplyinfoEntity.class);
    Fetch<TBusApplyinfoEntity, TBusScheduleRelaEntity> scheduleFetch = applyRoot
            .fetch(TBusApplyinfoEntity_.schedule, JoinType.LEFT);
    Join<TBusApplyinfoEntity, TBusScheduleRelaEntity> scheduleJoin = (Join<TBusApplyinfoEntity, TBusScheduleRelaEntity>) scheduleFetch;
    Predicate predicate = cb.conjunction();
    predicate = cb.and(predicate, cb.equal(scheduleJoin.get(TBusScheduleRelaEntity_.uuid), scheduleId));
    cq.where(predicate);/* w ww.  j  a va2 s  .com*/
    return em.createQuery(cq).getResultList();
}

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 w  ww.  jav a2 s.co m

    } 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:com.yunguchang.data.ApplicationRepository.java

public List<TBusApplyinfoEntity> getApplicationWithDetailByScheduleId(String scheduleId,
        PrincipalExt principalExt) {//from w  ww  . ja va 2  s .  c o m
    applySecurityFilter("applications", principalExt);

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<TBusApplyinfoEntity> cq = cb.createQuery(TBusApplyinfoEntity.class);
    Root<TBusApplyinfoEntity> applyRoot = cq.from(TBusApplyinfoEntity.class);
    Fetch<TBusApplyinfoEntity, TBusScheduleRelaEntity> scheduleFetch = applyRoot
            .fetch(TBusApplyinfoEntity_.schedule, JoinType.LEFT);
    applyRoot.fetch(TBusApplyinfoEntity_.fleet);
    applyRoot.fetch(TBusApplyinfoEntity_.passenger);
    applyRoot.fetch(TBusApplyinfoEntity_.coordinator);
    applyRoot.fetch(TBusApplyinfoEntity_.department);
    Join<TBusApplyinfoEntity, TBusScheduleRelaEntity> scheduleJoin = (Join<TBusApplyinfoEntity, TBusScheduleRelaEntity>) scheduleFetch;
    Predicate predicate = cb.conjunction();
    predicate = cb.and(predicate, cb.equal(scheduleJoin.get(TBusScheduleRelaEntity_.uuid), scheduleId));
    cq.where(predicate);
    return em.createQuery(cq).getResultList();
}

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

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

    List<HotelInfo> hotelInfos = null;

    try {//from w  ww. j  ava  2 s  .  c o  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:org.oncoblocks.centromere.jpa.test.JpaRepositoryTests.java

@Test
public void joinTest() throws Exception {
    Specification<EntrezGene> specification = new Specification<EntrezGene>() {
        @Override//from   www .  j a  v a  2s . 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:com.yunguchang.data.ApplicationRepository.java

public List<TAzCarinfoEntity> listAllCandidateCars(String[] applicationIds, String keyword, Integer offset,
        Integer limit, PrincipalExt principalExt) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<TAzCarinfoEntity> cq = cb.createQuery(TAzCarinfoEntity.class);
    Root<TAzCarinfoEntity> carRoot = cq.from(TAzCarinfoEntity.class);
    carRoot.fetch(TAzCarinfoEntity_.driver, JoinType.LEFT);

    cq.select(carRoot);/*www .  j a va  2  s  .  c om*/
    Subquery<TBusScheduleCarEntity> overlapScheduleCarSubQuery = cq.subquery(TBusScheduleCarEntity.class);

    applyOverlapScheduleCarSubquery(overlapScheduleCarSubQuery, applicationIds, carRoot, null, cb,
            principalExt);
    Predicate predicate = cb.and(cb.equal(carRoot.get(TAzCarinfoEntity_.clzt), "02"),
            cb.or(cb.equal(carRoot.get(TAzCarinfoEntity_.repairingState), RepairingState.NONE.id()),
                    cb.isNull(carRoot.get(TAzCarinfoEntity_.repairingState))

            ), cb.not(cb.exists(overlapScheduleCarSubQuery))

    );

    if (keyword != null) {
        predicate = cb.and(predicate,
                cb.or(cb.like(carRoot.get(TAzCarinfoEntity_.sysOrg).get(TSysOrgEntity_.orgname),
                        "%" + keyword + "%"),
                        cb.like(carRoot.get(TAzCarinfoEntity_.cphm), "%" + keyword + "%")));
    }

    cq.where(predicate);
    cq.orderBy(cb.asc(carRoot.get(TAzCarinfoEntity_.cphm)));
    TypedQuery<TAzCarinfoEntity> query = em.createQuery(cq);
    if (offset != null) {
        query.setFirstResult(offset);
    }

    if (limit != null) {
        query.setMaxResults(limit);
    }

    applySecurityFilter("cars", principalExt);

    return query.getResultList();
}

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   ww  w  . j a  v a 2 s  .  c  o m
    }

    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);
}