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:com.ocs.dynamo.dao.query.FetchJoinInformation.java

/**
 * Constructor - defaults to left join
 * 
 * @param property
 */
public FetchJoinInformation(String property) {
    this(property, JoinType.LEFT);
}

From source file:com.goodhuddle.huddle.repository.MemberSpecification.java

public static Specification<Member> search(final Huddle huddle, final SearchMembersRequest request) {
    return new Specification<Member>() {
        @Override//from   w  w w  . j a  v  a  2 s  . co m
        public Predicate toPredicate(Root<Member> member, CriteriaQuery<?> query, CriteriaBuilder builder) {

            Predicate conjunction = builder.conjunction();

            // huddle
            conjunction.getExpressions().add(builder.equal(member.get("huddle"), huddle));

            // keywords

            if (StringUtils.isNotBlank(request.getKeywords())) {
                String[] terms = StringUtils.split(request.getKeywords());
                for (String keyword : terms) {
                    if (keyword != null && keyword.length() > 0) {

                        String matchTerm = "%" + keyword.toLowerCase() + "%";
                        conjunction.getExpressions().add(builder.or(
                                builder.like(builder.lower(member.<String>get("username")), matchTerm),
                                builder.like(builder.lower(member.<String>get("email")), matchTerm),
                                builder.like(builder.lower(member.<String>get("firstName")), matchTerm),
                                builder.like(builder.lower(member.<String>get("lastName")), matchTerm)));
                    }
                }
            }

            // security groups

            if (CollectionUtils.isNotEmpty(request.getSecurityGroupIds())) {

                Join<Object, Object> securityGroup = member.join("securityGroup",
                        request.isIncludeNoAccess() ? JoinType.LEFT : JoinType.INNER);

                Predicate disjunction = builder.disjunction();
                for (Long id : request.getSecurityGroupIds()) {
                    disjunction.getExpressions().add(builder.equal(securityGroup.get("id"), id));
                }
                if (request.isIncludeNoAccess()) {
                    disjunction.getExpressions().add(builder.isNull(securityGroup.get("id")));
                }
                conjunction.getExpressions().add(disjunction);

            } else if (request.isIncludeNoAccess()) {

                conjunction.getExpressions().add(builder.isNull(member.get("securityGroup")));

            }

            // tags

            MemberTagFilter tagFilter = request.getTags();
            if (tagFilter != null) {

                if (tagFilter.getIncluded() != null) {

                    if (CollectionUtils.isNotEmpty(tagFilter.getIncluded().getTagIds())) {

                        MemberTagFilter.TagSet included = request.getTags().getIncluded();
                        MatchType matchType = included.getMatchType();
                        Predicate tagPredicate = matchType.equals(MatchType.all) ? builder.conjunction()
                                : builder.disjunction();

                        for (Long tagId : included.getTagIds()) {
                            Subquery<Member> sq = query.subquery(Member.class);
                            Root<Member> subMember = sq.from(Member.class);
                            Join<Member, Tag> tag = subMember.join("tags");
                            sq.select(subMember).where(builder.equal(tag.get("id"), tagId));
                            tagPredicate.getExpressions().add(builder.in(member).value(sq));
                        }

                        conjunction.getExpressions().add(tagPredicate);
                    }
                }

                if (tagFilter.getExcluded() != null) {

                    if (CollectionUtils.isNotEmpty(tagFilter.getExcluded().getTagIds())) {

                        MemberTagFilter.TagSet excluded = request.getTags().getExcluded();
                        MatchType matchType = excluded.getMatchType();
                        Predicate tagPredicate = matchType.equals(MatchType.all) ? builder.disjunction()
                                : builder.conjunction();

                        for (Long tagId : excluded.getTagIds()) {
                            Subquery<Member> sq = query.subquery(Member.class);
                            Root<Member> subMember = sq.from(Member.class);
                            Join<Member, Tag> tag = subMember.join("tags");
                            sq.select(subMember).where(builder.equal(tag.get("id"), tagId));
                            tagPredicate.getExpressions().add(builder.in(member).value(sq).not());
                        }

                        conjunction.getExpressions().add(tagPredicate);
                    }
                }

            }

            return conjunction;
        }
    };
}

From source file:net.kaczmarzyk.spring.data.jpa.web.SpecificationArgumentResolverTest.java

@Test
public void resolvesJoinFetchForSimpleSpec() throws Exception {
    MethodParameter param = MethodParameter.forMethodOrConstructor(testMethod("testMethod"), 0);
    NativeWebRequest req = mock(NativeWebRequest.class);
    when(req.getParameterValues("path1")).thenReturn(new String[] { "value1" });

    Specification<?> resolved = (Specification<?>) resolver.resolveArgument(param, null, req, null);

    assertThat(resolved).isInstanceOf(Conjunction.class);

    Collection<Specification<?>> innerSpecs = ReflectionUtils.get(resolved, "innerSpecs");

    assertThat(innerSpecs).hasSize(2).contains(new Like<Object>("path1", new String[] { "value1" })).contains(
            new net.kaczmarzyk.spring.data.jpa.domain.JoinFetch<Object>(new String[] { "fetch1", "fetch2" },
                    JoinType.LEFT));
}

From source file:com.expressui.sample.dao.query.RecentContactsQuery.java

@Override
public Path buildOrderBy(Root<Contact> contact) {
    if (getOrderByPropertyId().equals("mailingAddress.country")) {
        return contact.join("mailingAddress", JoinType.LEFT).join("country", JoinType.LEFT);
    } else if (getOrderByPropertyId().equals("mailingAddress.street")) {
        return contact.join("mailingAddress", JoinType.LEFT).get("street");
    } else if (getOrderByPropertyId().equals("mailingAddress.city")) {
        return contact.join("mailingAddress", JoinType.LEFT).get("city");
    } else if (getOrderByPropertyId().equals("mailingAddress.state.code")) {
        return contact.join("mailingAddress", JoinType.LEFT).join("state", JoinType.LEFT).get("code");
    } else {//from   ww w  . j av a  2  s  .c  om
        return null;
    }
}

From source file:com.hengyi.japp.execution.Util.java

public static void queryCommand(CriteriaBuilder cb, CriteriaQuery<?> cq, Root<Task> root,
        TaskQueryCommand command) {/*from ww w. ja va  2s .  c o m*/
    Predicate p1 = cb.equal(root.get(Task_.charger), command.getOperator());
    ListJoin<Task, Operator> joinFollowers = root.join(Task_.followers, JoinType.LEFT);
    Predicate p2 = cb.equal(joinFollowers.get(Operator_.id), command.getOperator().getId());
    ListJoin<Task, Operator> joinExecutors = root.join(Task_.executors, JoinType.LEFT);
    Predicate p3 = cb.equal(joinExecutors.get(Operator_.id), command.getOperator().getId());
    Predicate p = cb.or(p1, p2, p3);
    if (command.getExecutor() != null) {
        p = cb.and(p, cb.equal(p, cb.isMember(command.getExecutor(), root.get(Task_.executors))));
    }
    if (command.getCustomer() != null) {
        p = cb.and(p, cb.equal(root.get(Task_.customer), command.getCustomer()));
    }
    if (!isBlank(command.getContent())) {
        p = cb.and(p, cb.like(root.get(Task_.content), command.getContentQuery()));
    }
    Collection<TaskType> TaskTypes = command.getTypes();
    if (TaskTypes != null && !TaskTypes.isEmpty()) {
        p = cb.and(p, root.get(Task_.type).in(TaskTypes));
    }
    Collection<TaskStatus> statuses = command.getStatuses();
    if (statuses != null && !statuses.isEmpty()) {
        p = cb.and(p, root.get(Task_.status).in(statuses));
    }
    if (command.getCreateDate() != null) {
        Date createDateStart = LocalDate.fromDateFields(command.getCreateDate()).toDate();
        Date createDateEnd = LocalDate.fromDateFields(command.getCreateDate()).plusDays(1).toDate();
        p = cb.and(p, cb.between(root.get(Task_.logInfo).get(LogInfo_.createDateTime), createDateStart,
                createDateEnd));
        // TODO timestamp date convert
        //p = cb.and(p, cb.equal(root.get(Task_.logInfo).get(LogInfo_.createDateTime).as(java.sql.Date.class), command.getCreateDate()));
    }
    cq.where(p);
}

From source file:se.inera.intyg.intygstjanst.persistence.model.dao.impl.CertificateDaoImpl.java

@Override
public List<Certificate> findCertificate(Personnummer civicRegistrationNumber, List<String> types,
        LocalDate fromDate, LocalDate toDate, List<String> careUnits) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Certificate> query = criteriaBuilder.createQuery(Certificate.class);
    Root<Certificate> root = query.from(Certificate.class);

    root.fetch("states", JoinType.LEFT);

    if (civicRegistrationNumber == null) {
        return Collections.emptyList();
    }/*from   w w  w .  j av  a2s  .  c  om*/

    List<Predicate> predicates = new ArrayList<>();

    // meta data has to match civic registration number
    predicates.add(criteriaBuilder.equal(root.get("civicRegistrationNumber"),
            DaoUtil.formatPnrForPersistence(civicRegistrationNumber)));

    // filter by certificate types
    if (types != null && !types.isEmpty()) {
        predicates.add(criteriaBuilder.lower(root.<String>get("type")).in(toLowerCase(types)));
    }

    // filter by care unit
    if (careUnits != null && !careUnits.isEmpty()) {
        predicates.add(root.<String>get("careUnitId").in(careUnits));
    }

    query.where(predicates.toArray(new Predicate[predicates.size()]));

    // order by signed date
    query.orderBy(criteriaBuilder.asc(root.get("signedDate")));

    List<Certificate> tmpResult = entityManager.createQuery(query).getResultList();
    List<Certificate> result = filterDuplicates(tmpResult);

    // expect a small number, so lets filter in memory
    return new DateFilter(result).filter(fromDate, toDate);
}

From source file:com.expressui.sample.view.dashboard.RecentContactsQuery.java

@Override
public Path buildOrderBy(Root<Contact> rootEntity) {
    if (getOrderByPropertyId().equals("mailingAddress.country")) {
        return rootEntity.join("mailingAddress", JoinType.LEFT).join("country", JoinType.LEFT);
    } else if (getOrderByPropertyId().equals("mailingAddress.street")) {
        return rootEntity.join("mailingAddress", JoinType.LEFT).get("street");
    } else if (getOrderByPropertyId().equals("mailingAddress.city")) {
        return rootEntity.join("mailingAddress", JoinType.LEFT).get("city");
    } else if (getOrderByPropertyId().equals("mailingAddress.state.code")) {
        return rootEntity.join("mailingAddress", JoinType.LEFT).join("state", JoinType.LEFT).get("code");
    } else {//  w ww  . ja  v a2 s. c om
        return null;
    }
}

From source file:com.expressui.sample.dao.query.RecentContactsQuery.java

@Override
public void addFetchJoins(Root<Contact> contact) {
    Fetch mailingAddress = contact.fetch("mailingAddress", JoinType.LEFT);
    mailingAddress.fetch("state", JoinType.LEFT);
    mailingAddress.fetch("country", JoinType.LEFT);
}

From source file:com.home.ln_spring.ch10.service.jpa.ContactServiceImplOld.java

@Override
@Transactional(readOnly = true)// w  w w .  j  a v a2 s .  c o m
public List<Contact> findByCriteriaQuery(String firstName, String lastName) {
    log.info("Finding contact for firstName: " + firstName + " and lastName: " + lastName);

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Contact> criteriaQuery = cb.createQuery(Contact.class);
    Root<Contact> contactRoot = criteriaQuery.from(Contact.class);
    contactRoot.fetch(Contact_.contactTelDetails, JoinType.LEFT);
    contactRoot.fetch(Contact_.hobbies, JoinType.LEFT);

    criteriaQuery.select(contactRoot).distinct(true);

    Predicate criteria = cb.conjunction();
    if (firstName != null) {
        Predicate p = cb.equal(contactRoot.get(Contact_.firstName), firstName);
        criteria = cb.and(criteria, p);
    }

    if (lastName != null) {
        Predicate p = cb.equal(contactRoot.get(Contact_.lastName), lastName);
        criteria = cb.and(criteria, p);
    }

    criteriaQuery.where(criteria);
    List<Contact> result = em.createQuery(criteriaQuery).getResultList();
    return result;
}

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

public List<TBusApplyinfoEntity> getAllApplications(String coordinatorUserId, String reasonType, String status,
        DateTime startBefore, DateTime startAfter, DateTime endBefore, DateTime endAfter, Integer offset,
        Integer limit, OrderByParam orderByParam, PrincipalExt principalExt) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<TBusApplyinfoEntity> cq = cb.createQuery(TBusApplyinfoEntity.class);
    Root<TBusApplyinfoEntity> applyRoot = cq.from(TBusApplyinfoEntity.class);
    applyRoot.fetch(TBusApplyinfoEntity_.passenger);
    Fetch<TBusApplyinfoEntity, TSysUserEntity> fetchCoordinator = applyRoot
            .fetch(TBusApplyinfoEntity_.coordinator);
    applyRoot.fetch(TBusApplyinfoEntity_.department);
    Fetch<TBusApplyinfoEntity, TBusScheduleRelaEntity> scheduleFetch = applyRoot
            .fetch(TBusApplyinfoEntity_.schedule, JoinType.LEFT);
    scheduleFetch.fetch(TBusScheduleRelaEntity_.senduser, JoinType.LEFT);
    scheduleFetch.fetch(TBusScheduleRelaEntity_.reciveuser, JoinType.LEFT);
    Fetch<TBusScheduleRelaEntity, TBusScheduleCarEntity> fetchScheduleCar = scheduleFetch
            .fetch(TBusScheduleRelaEntity_.scheduleCars, JoinType.LEFT);
    fetchScheduleCar.fetch(TBusScheduleCarEntity_.car, JoinType.LEFT).fetch(TAzCarinfoEntity_.depot,
            JoinType.LEFT);/* w  ww.  j  a v  a2 s  .c o  m*/
    fetchScheduleCar.fetch(TBusScheduleCarEntity_.driver, JoinType.LEFT).fetch(TRsDriverinfoEntity_.department,
            JoinType.LEFT);
    Predicate predicate = cb.conjunction();
    if (coordinatorUserId != null) {
        Join<TBusApplyinfoEntity, TSysUserEntity> joinCoordinator = (Join<TBusApplyinfoEntity, TSysUserEntity>) fetchCoordinator;
        predicate = cb.and(predicate, cb.equal(joinCoordinator.get(TSysUserEntity_.userid), coordinatorUserId));
    }
    if (reasonType != null) {
        predicate = cb.and(predicate, cb.equal(applyRoot.get(TBusApplyinfoEntity_.reason), reasonType));
    }
    if (status != null) {
        if (status.indexOf(":") < 0) {
            predicate = cb.and(predicate, cb.equal(applyRoot.get(TBusApplyinfoEntity_.status), status));
        } else {
            String[] statusList = status.split(":");
            predicate = cb.and(predicate,
                    applyRoot.get(TBusApplyinfoEntity_.status).in(Arrays.asList(statusList)));
        }
    }

    if (startBefore != null) {
        predicate = cb.and(predicate,
                cb.lessThanOrEqualTo(applyRoot.get(TBusApplyinfoEntity_.begintime), startBefore));
    }

    if (startAfter != null) {
        predicate = cb.and(predicate,
                cb.greaterThanOrEqualTo(applyRoot.get(TBusApplyinfoEntity_.begintime), startAfter));
    }

    if (endBefore != null) {
        predicate = cb.and(predicate,
                cb.lessThanOrEqualTo(applyRoot.get(TBusApplyinfoEntity_.endtime), endBefore));
    }

    if (endAfter != null) {
        predicate = cb.and(predicate,
                cb.greaterThanOrEqualTo(applyRoot.get(TBusApplyinfoEntity_.endtime), endAfter));
    }

    cq.where(predicate);

    List<Order> orders = new ArrayList<>();
    if (orderByParam != null) {
        for (OrderByParam.OrderBy orderBy : orderByParam.getOrderBies()) {
            Order order = null;
            if (orderBy.getFiled().toLowerCase().equals("start".toLowerCase())) {
                order = cb.desc(applyRoot.get(TBusApplyinfoEntity_.begintime));
            }
            if (order != null && !orderBy.isAsc()) {
                order = order.reverse();
            }
            if (order != null) {
                orders.add(order);
            }
        }

    }
    if (orders.size() == 0) {
        cq.orderBy(cb.desc(applyRoot.get(TBusApplyinfoEntity_.begintime)));
    } else {
        cq.orderBy(orders);
    }

    TypedQuery<TBusApplyinfoEntity> query = em.createQuery(cq);

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

    applySecurityFilter("applications", principalExt);

    return query.getResultList();
}