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

public List<TBusApproveSugEntity> listApplyApproveInfo(DateTime startTime, DateTime endTime,
        PrincipalExt principalExtOrNull) {
    if (startTime == null) {
        startTime = DateTimeUtil.appStartTime;
    }/*  ww w . j  a va  2s  . com*/
    if (endTime == null) {
        endTime = DateTimeUtil.appEndTime;
    }

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<TBusApproveSugEntity> cq = cb.createQuery(TBusApproveSugEntity.class);
    Root<TBusApproveSugEntity> approveRoot = cq.from(TBusApproveSugEntity.class);
    approveRoot.fetch(TBusApproveSugEntity_.application);
    approveRoot.fetch(TBusApproveSugEntity_.user, JoinType.LEFT);
    cq.select(approveRoot);

    Predicate predicate = cb.and(
            cb.between(approveRoot.get(TBusApproveSugEntity_.operatedate), new Timestamp(startTime.getMillis()),
                    new Timestamp(endTime.getMillis())),
            cb.or(cb.isNull(approveRoot.get(TBusApproveSugEntity_.updateBySync)),
                    cb.isFalse(approveRoot.get(TBusApproveSugEntity_.updateBySync))));

    cq.where(predicate);

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

    applySecurityFilter("applications", principalExtOrNull);
    return query.getResultList();
}

From source file:ca.uhn.fhir.jpa.dao.SearchBuilder.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  av  a  2s. c  o  m
    }

    if (BaseResource.SP_RES_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, thePredicates);
        return;
    }

    if (Constants.PARAM_LASTUPDATED.equals(theSort.getParamName())) {
        if (theSort.getOrder() == null || theSort.getOrder() == SortOrderEnum.ASC) {
            theOrders.add(theBuilder.asc(theFrom.get("myUpdated")));
        } else {
            theOrders.add(theBuilder.desc(theFrom.get("myUpdated")));
        }

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

    RuntimeSearchParam param = 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 = new String[] { "myValueExact" };
        break;
    case DATE:
        joinAttrName = "myParamsDate";
        sortAttrName = new String[] { "myValueLow" };
        break;
    case REFERENCE:
        joinAttrName = "myResourceLinks";
        sortAttrName = new String[] { "myTargetResourcePid" };
        break;
    case TOKEN:
        joinAttrName = "myParamsToken";
        sortAttrName = new String[] { "mySystem", "myValue" };
        break;
    case NUMBER:
        joinAttrName = "myParamsNumber";
        sortAttrName = new String[] { "myValue" };
        break;
    case URI:
        joinAttrName = "myParamsUri";
        sortAttrName = new String[] { "myUri" };
        break;
    case QUANTITY:
        joinAttrName = "myParamsQuantity";
        sortAttrName = new String[] { "myValue" };
        break;
    default:
        throw new InvalidRequestException("This server does not support _sort specifications of type "
                + param.getParamType() + " - Can't serve _sort=" + theSort.getParamName());
    }

    From<?, ?> stringJoin = theFrom.join(joinAttrName, JoinType.INNER);

    if (param.getParamType() == RestSearchParameterTypeEnum.REFERENCE) {
        thePredicates.add(stringJoin.get("mySourcePath").as(String.class).in(param.getPathsSplit()));
    } else {
        thePredicates.add(theBuilder.equal(stringJoin.get("myParamName"), theSort.getParamName()));
    }

    // Predicate p = theBuilder.equal(stringJoin.get("myParamName"), theSort.getParamName());
    // Predicate pn = theBuilder.isNull(stringJoin.get("myParamName"));
    // thePredicates.add(theBuilder.or(p, pn));

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

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

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

public IBundleProvider search(final SearchParameterMap theParams) {
    myParams = theParams;/*from   w  w  w . ja  v a 2s .c  o m*/
    StopWatch w = new StopWatch();

    doInitializeSearch();

    DateRangeParam lu = theParams.getLastUpdated();

    // Collection<Long> loadPids;
    if (theParams.getEverythingMode() != null) {

        Long pid = null;
        if (theParams.get(BaseResource.SP_RES_ID) != null) {
            StringParam idParm = (StringParam) theParams.get(BaseResource.SP_RES_ID).get(0).get(0);
            pid = BaseHapiFhirDao.translateForcedIdToPid(myResourceName, idParm.getValue(), myForcedIdDao);
        }

        if (theParams.containsKey(Constants.PARAM_CONTENT) || theParams.containsKey(Constants.PARAM_TEXT)) {
            List<Long> pids = mySearchDao.everything(myResourceName, theParams);
            if (pids.isEmpty()) {
                return doReturnProvider();
            }

            doSetPids(pids);

        } else {
            CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();
            CriteriaQuery<Tuple> cq = builder.createTupleQuery();
            Root<ResourceTable> from = cq.from(ResourceTable.class);
            List<Predicate> predicates = new ArrayList<Predicate>();
            if (pid != null) {
                predicates.add(builder.equal(from.get("myId"), pid));
            }
            predicates.add(builder.equal(from.get("myResourceType"), myResourceName));
            predicates.add(builder.isNull(from.get("myDeleted")));
            cq.where(builder.and(SearchBuilder.toArray(predicates)));

            Join<Object, Object> join = from.join("myIncomingResourceLinks", JoinType.LEFT);
            cq.multiselect(from.get("myId").as(Long.class), join.get("mySourceResourcePid").as(Long.class));

            TypedQuery<Tuple> query = myEntityManager.createQuery(cq);
            Set<Long> pids = new HashSet<Long>();
            for (Tuple next : query.getResultList()) {
                pids.add(next.get(0, Long.class));
                Long nextLong = next.get(1, Long.class);
                if (nextLong != null) {
                    pids.add(nextLong);
                }
            }
            doSetPids(pids);

        }

    } else if (theParams.isEmpty()) {

        TypedQuery<Long> query = createSearchAllByTypeQuery(lu);
        doSetPids(query.getResultList());

    } else {

        if (mySearchDao == null) {
            if (theParams.containsKey(Constants.PARAM_TEXT)) {
                throw new InvalidRequestException(
                        "Fulltext search is not enabled on this service, can not process parameter: "
                                + Constants.PARAM_TEXT);
            } else if (theParams.containsKey(Constants.PARAM_CONTENT)) {
                throw new InvalidRequestException(
                        "Fulltext search is not enabled on this service, can not process parameter: "
                                + Constants.PARAM_CONTENT);
            }
        } else {
            List<Long> searchResultPids = mySearchDao.search(myResourceName, theParams);
            if (searchResultPids != null) {
                if (searchResultPids.isEmpty()) {
                    return doReturnProvider();
                }
                doSetPids(searchResultPids);
            }
        }

        if (!theParams.isEmpty()) {
            searchForIdsWithAndOr(theParams, lu);
        }

    }

    // // Load _include and _revinclude before filter and sort in everything mode
    // if (theParams.getEverythingMode() != null) {
    // if (theParams.getRevIncludes() != null && theParams.getRevIncludes().isEmpty() == false) {
    // loadPids.addAll(loadReverseIncludes(loadPids, theParams.getRevIncludes(), true,
    // theParams.getEverythingMode()));
    // loadPids.addAll(loadReverseIncludes(loadPids, theParams.getIncludes(), false, theParams.getEverythingMode()));
    // }
    // }

    if (doHaveNoResults()) {
        return doReturnProvider();
    }

    // Handle _lastUpdated
    if (lu != null) {
        filterResourceIdsByLastUpdated(lu);

        if (doHaveNoResults()) {
            return doReturnProvider();
        }
    }

    // Handle sorting if any was provided
    processSort(theParams);

    ourLog.info(" {} on {} in {}ms", new Object[] { myResourceName, theParams, w.getMillisAndRestart() });
    return doReturnProvider();
}

From source file:org.apereo.portal.persondir.dao.jpa.JpaLocalAccountDaoImpl.java

@Override
public void afterPropertiesSet() throws Exception {
    this.nameParameter = this.createParameterExpression(String.class, "name");

    this.findAllAccountsQuery = this
            .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<LocalAccountPersonImpl>>() {
                @Override//  w w  w.  ja v a  2 s .  c o  m
                public CriteriaQuery<LocalAccountPersonImpl> apply(CriteriaBuilder cb) {
                    final CriteriaQuery<LocalAccountPersonImpl> criteriaQuery = cb
                            .createQuery(LocalAccountPersonImpl.class);
                    final Root<LocalAccountPersonImpl> accountRoot = criteriaQuery
                            .from(LocalAccountPersonImpl.class);
                    accountRoot.fetch(LocalAccountPersonImpl_.attributes, JoinType.LEFT)
                            .fetch(LocalAccountPersonAttributeImpl_.values, JoinType.LEFT);
                    criteriaQuery.select(accountRoot);

                    return criteriaQuery;
                }
            });

    this.findAccountByNameQuery = this
            .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<LocalAccountPersonImpl>>() {
                @Override
                public CriteriaQuery<LocalAccountPersonImpl> apply(CriteriaBuilder cb) {
                    final CriteriaQuery<LocalAccountPersonImpl> criteriaQuery = cb
                            .createQuery(LocalAccountPersonImpl.class);
                    final Root<LocalAccountPersonImpl> accountRoot = criteriaQuery
                            .from(LocalAccountPersonImpl.class);
                    accountRoot.fetch(LocalAccountPersonImpl_.attributes, JoinType.LEFT)
                            .fetch(LocalAccountPersonAttributeImpl_.values, JoinType.LEFT);
                    criteriaQuery.select(accountRoot);
                    criteriaQuery.where(cb.equal(accountRoot.get(LocalAccountPersonImpl_.name), nameParameter));

                    return criteriaQuery;
                }
            });

    this.findAvailableAttributesQuery = this
            .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<String>>() {
                @Override
                public CriteriaQuery<String> apply(CriteriaBuilder cb) {
                    final CriteriaQuery<String> criteriaQuery = cb.createQuery(String.class);
                    final Root<LocalAccountPersonAttributeImpl> accountRoot = criteriaQuery
                            .from(LocalAccountPersonAttributeImpl.class);
                    criteriaQuery.select(accountRoot.get(LocalAccountPersonAttributeImpl_.name));
                    criteriaQuery.distinct(true);

                    return criteriaQuery;
                }
            });
}

From source file:org.apereo.portal.portlet.dao.jpa.JpaPortletDefinitionDao.java

/**
 * Add all the fetches needed for completely loading the object graph
 *//*  www  .j  a va 2  s .c om*/
protected void addFetches(final Root<PortletDefinitionImpl> definitionRoot) {
    definitionRoot.fetch(PortletDefinitionImpl_.portletPreferences, JoinType.LEFT)
            .fetch(PortletPreferencesImpl_.portletPreferences, JoinType.LEFT)
            .fetch(PortletPreferenceImpl_.values, JoinType.LEFT);
    definitionRoot.fetch(PortletDefinitionImpl_.parameters, JoinType.LEFT);
    definitionRoot.fetch(PortletDefinitionImpl_.localizations, JoinType.LEFT);
}

From source file:org.apereo.portal.portlet.dao.jpa.JpaPortletEntityDao.java

/**
 * Add all the fetches needed for completely loading the object graph
 *//*  w w w.  j  av  a  2 s.  co  m*/
protected void addFetches(final Root<PortletEntityImpl> definitionRoot) {
    definitionRoot.fetch(PortletEntityImpl_.portletPreferences, JoinType.LEFT)
            .fetch(PortletPreferencesImpl_.portletPreferences, JoinType.LEFT)
            .fetch(PortletPreferenceImpl_.values, JoinType.LEFT);
    definitionRoot.fetch(PortletEntityImpl_.windowStates, JoinType.LEFT);
}

From source file:org.artificer.repository.hibernate.query.ArtificerToHibernateQueryVisitor.java

/**
 * @see org.artificer.common.query.xpath.visitors.XPathVisitor#visit(org.artificer.common.query.xpath.ast.SubartifactSet)
 *//*from   ww  w . j a v a  2 s  . com*/
@Override
public void visit(SubartifactSet node) {
    if (node.getFunctionCall() != null) {
        node.getFunctionCall().accept(this);
    } else if (node.getRelationshipPath() != null) {
        From oldRootContext = from;

        if (node.getRelationshipPath().getRelationshipType().equalsIgnoreCase("relatedDocument")) {
            // derivedFrom
            // TODO: Should this really be LEFT?
            from = from.join("derivedFrom", JoinType.LEFT);

            // Now add any additional predicates included.
            if (node.getPredicate() != null) {
                node.getPredicate().accept(this);
            }
        } else if (node.getRelationshipPath().getRelationshipType().equalsIgnoreCase("expandedFromDocument")
                || node.getRelationshipPath().getRelationshipType().equalsIgnoreCase("expandedFromArchive")) {
            // expandedFrom
            from = from.join("expandedFrom");

            // Now add any additional predicates included.
            if (node.getPredicate() != null) {
                node.getPredicate().accept(this);
            }
        } else {
            // Relationship within a predicate.
            // Create a subquery and 'exists' conditional.  The subquery is much easier to handle, later on, if this
            // predicate is negated, as opposed to removing the inner join or messing with left joins.

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

            Subquery relationshipSubquery = query.subquery(ArtificerRelationship.class);
            relationshipFrom = relationshipSubquery.from(ArtificerRelationship.class);
            targetFrom = relationshipFrom.join("targets");
            relationshipSubquery.select(relationshipFrom.get("id"));

            Join relationshipOwnerJoin = relationshipFrom.join("owner");
            predicates.add(criteriaBuilder.equal(relationshipOwnerJoin.get("id"), oldRootContext.get("id")));

            from = relationshipFrom;

            // process constraints on the relationship itself
            node.getRelationshipPath().accept(this);

            // context now needs to be the relationship targets

            from = targetFrom.join("target");

            // Now add any additional predicates included.
            if (node.getPredicate() != null) {
                node.getPredicate().accept(this);
            }

            // Add predicates to subquery
            relationshipSubquery.where(compileAnd(predicates));

            predicates = oldPredicates;

            // Add 'exists' predicate (using subquery) to original list
            predicates.add(criteriaBuilder.exists(relationshipSubquery));
        }

        // restore the original selector (since the relationship was in a predicate, not a path)
        from = oldRootContext;

        if (node.getSubartifactSet() != null) {
            throw new RuntimeException(Messages.i18n.format("XP_MULTILEVEL_SUBARTYSETS_NOT_SUPPORTED"));
        }
    }
}

From source file:org.batoo.jpa.benchmark.BenchmarkTest.java

private void test(final EntityManagerFactory emf, Queue<Runnable> workQueue, int length) {
    final CriteriaBuilder cb = emf.getCriteriaBuilder();
    final CriteriaQuery<Address> cq = cb.createQuery(Address.class);

    final Root<Person> r = cq.from(Person.class);
    final Join<Person, Address> a = r.join("addresses");
    a.fetch("country", JoinType.LEFT);
    a.fetch("person", JoinType.LEFT);
    cq.select(a);//  ww w  .j a  va  2 s. c  om

    final ParameterExpression<Person> p = cb.parameter(Person.class);
    cq.where(cb.equal(r, p));

    for (int i = 0; i < length; i++) {
        workQueue.add(new Runnable() {

            @Override
            public void run() {
                try {
                    BenchmarkTest.this.singleTest(emf, BenchmarkTest.this.createPersons(), cq, p);
                } catch (final Exception e) {
                    BenchmarkTest.LOG.error(e, "Error while running the test");
                }
            }
        });
    }
}

From source file:org.batoo.jpa.core.impl.criteria.join.AbstractJoin.java

/**
 * {@inheritDoc}/*  w w  w.  jav  a 2s.co  m*/
 * 
 */
@Override
public String generateJpqlJoins(AbstractCriteriaQueryImpl<?> criteriaQuery) {
    this.ensureAlias(criteriaQuery);

    final StringBuilder builder = new StringBuilder();

    builder.append(this.joinType == JoinType.LEFT ? "left" : "inner");
    builder.append(" join ") //
            .append(this.getParent().getAlias()).append(".").append(this.mapping.getAttribute().getName()) //
            .append(" as ").append(this.getAlias());

    final String joins = super.generateJpqlJoins(criteriaQuery);
    if (StringUtils.isNotBlank(joins)) {
        builder.append("\n").append(joins);
    }

    return builder.toString();
}

From source file:org.batoo.jpa.core.impl.criteria.join.FetchParentImpl.java

/**
 * {@inheritDoc}/*from  w  w w . ja  v a2s  .  c om*/
 * 
 */
@Override
public final <Y> FetchImpl<X, Y> fetch(PluralAttribute<? super X, ?, Y> attribute) {
    return this.fetch(attribute, JoinType.LEFT);
}