Java Examples for javax.persistence.criteria.Join

The following java examples will help you to understand the usage of javax.persistence.criteria.Join. These source code samples are taken from different open source projects.

Example 1
Project: TechnologyReadinessTool-master  File: OrgDAOImpl.java View source code
@Override
public OrgDO getOrg(String code, Long scopeId) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<OrgDO> criteria = cb.createQuery(OrgDO.class);
    Root<OrgDO> org = criteria.from(OrgDO.class);
    Join<OrgDO, ScopeDO> scope = org.join(OrgDO_.scope);
    Join<ScopeDO, ScopeTypeDO> scopeType = scope.join(ScopeDO_.scopeType);
    Join<ScopeDO, ScopeTreeDO> scopeTree = scope.join(ScopeDO_.ancestorScopeTrees);
    Predicate typeClause = cb.equal(scopeType.get(ScopeTypeDO_.allowOrg), Short.valueOf("1"));
    Predicate pathClause = cb.equal(scopeTree.get(ScopeTreeDO_.scope).get(ScopeDO_.scopeId), scopeId);
    Predicate orgCode = cb.equal(org.get(OrgDO_.code), code);
    criteria.where(orgCode, typeClause, pathClause);
    return getSingleResult(em.createQuery(criteria));
}
Example 2
Project: VaadinUtils-master  File: JpaBaseDao.java View source code
public <V, J> List<E> findAllByAttributeJoin(SingularAttribute<E, J> joinAttr, SingularAttribute<J, V> vKey, V value, JoinType joinType) {
    CriteriaBuilder builder = getEntityManager().getCriteriaBuilder();
    CriteriaQuery<E> criteria = builder.createQuery(entityClass);
    Root<E> root = criteria.from(entityClass);
    Join<E, J> join = root.join(joinAttr, joinType);
    criteria.where(builder.equal(join.get(vKey), value));
    return getEntityManager().createQuery(criteria).getResultList();
}
Example 3
Project: activejpa-master  File: EntityCollection.java View source code
public long count(Filter filter) {
    filter.addCondition("id", parent.getId());
    CriteriaBuilder builder = getEntityManager().getCriteriaBuilder();
    CriteriaQuery<Long> cQuery = builder.createQuery(Long.class);
    Root<? extends Model> root = cQuery.from(parent.getClass());
    Join join = root.join(name);
    cQuery.select(builder.count(join));
    filter.constructQuery(builder, cQuery, root);
    TypedQuery<Long> query = createQuery(cQuery, filter);
    return query.getSingleResult();
}
Example 4
Project: gazpachoquest-master  File: JpaUtil.java View source code
/**
     * Convert the passed propertyPath into a JPA path.
     * <p>
     * Note: JPA will do joins if the property is in an associated entity.
     */
@SuppressWarnings("unchecked")
public static <E, F> Path<F> getPath(Root<E> root, List<Attribute<?, ?>> attributes) {
    Path<?> path = root;
    for (Attribute<?, ?> attribute : attributes) {
        boolean found = false;
        // handle case when order on already fetched attribute
        for (Fetch<E, ?> fetch : root.getFetches()) {
            if (attribute.getName().equals(fetch.getAttribute().getName()) && (fetch instanceof Join<?, ?>)) {
                path = (Join<E, ?>) fetch;
                found = true;
                break;
            }
        }
        for (Join<E, ?> join : root.getJoins()) {
            if (attribute.getName().equals(join.getAttribute().getName())) {
                path = join;
                found = true;
                break;
            }
        }
        if (!found) {
            path = path.get(attribute.getName());
        }
    }
    return (Path<F>) path;
}
Example 5
Project: HERD-master  File: EmrServiceTest.java View source code
/**
     * Returns a list of {@link EmrClusterCreationLogEntity} objects for the given cluster namespace, cluster definition name, and EMR cluster name. All the
     * given parameters are case insensitive. The returned list's order is not guaranteed.
     *
     * @param namespace - EMR cluster namespace
     * @param definitionName - EMR cluster definition name
     * @param clusterName - EMR cluster name
     *
     * @return list of EMR cluster creation logs
     */
protected List<EmrClusterCreationLogEntity> getEmrClusterCreationLogEntities(String namespace, String definitionName, String clusterName) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<EmrClusterCreationLogEntity> query = builder.createQuery(EmrClusterCreationLogEntity.class);
    Root<EmrClusterCreationLogEntity> emrClusterCreationLogEntity = query.from(EmrClusterCreationLogEntity.class);
    Join<?, NamespaceEntity> namespaceEntity = emrClusterCreationLogEntity.join(EmrClusterCreationLogEntity_.namespace);
    Predicate namespacePredicate = builder.equal(builder.upper(namespaceEntity.get(NamespaceEntity_.code)), namespace.toUpperCase());
    Predicate definitionNamePredicate = builder.equal(builder.upper(emrClusterCreationLogEntity.get(EmrClusterCreationLogEntity_.emrClusterDefinitionName)), definitionName.toUpperCase());
    Predicate clusterNamePredicate = builder.equal(builder.upper(emrClusterCreationLogEntity.get(EmrClusterCreationLogEntity_.emrClusterName)), clusterName.toUpperCase());
    query.select(emrClusterCreationLogEntity).where(builder.and(namespacePredicate, definitionNamePredicate, clusterNamePredicate));
    return entityManager.createQuery(query).getResultList();
}
Example 6
Project: hibernate-orm-master  File: AbstractFromImpl.java View source code
@Override
@SuppressWarnings({ "unchecked" })
public <X, Y> Join<X, Y> join(String attributeName, JoinType jt) {
    if (!canBeJoinSource()) {
        throw illegalJoin();
    }
    if (jt.equals(JoinType.RIGHT)) {
        throw new UnsupportedOperationException("RIGHT JOIN not supported");
    }
    final Attribute<X, ?> attribute = (Attribute<X, ?>) locateAttribute(attributeName);
    if (attribute.isCollection()) {
        final PluralAttribute pluralAttribute = (PluralAttribute) attribute;
        if (PluralAttribute.CollectionType.COLLECTION.equals(pluralAttribute.getCollectionType())) {
            return (Join<X, Y>) join((CollectionAttribute) attribute, jt);
        } else if (PluralAttribute.CollectionType.LIST.equals(pluralAttribute.getCollectionType())) {
            return (Join<X, Y>) join((ListAttribute) attribute, jt);
        } else if (PluralAttribute.CollectionType.SET.equals(pluralAttribute.getCollectionType())) {
            return (Join<X, Y>) join((SetAttribute) attribute, jt);
        } else {
            return (Join<X, Y>) join((MapAttribute) attribute, jt);
        }
    } else {
        return (Join<X, Y>) join((SingularAttribute) attribute, jt);
    }
}
Example 7
Project: arquillian-showcase-master  File: GameRepository.java View source code
public List<Game> fetchAllFor(Platform platform) {
    CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
    CriteriaQuery<Game> query = criteriaBuilder.createQuery(Game.class);
    Root<Game> fromGames = query.from(Game.class);
    Join<Game, Platform> platformsOfGame = fromGames.join(Game_.supportedPlatforms);
    Predicate givenPlatfromIsAssigned = criteriaBuilder.equal(platformsOfGame.get(Platform_.name), platform.getName());
    CriteriaQuery<Game> allGamesForGivenPlatfrom = query.select(fromGames).where(givenPlatfromIsAssigned);
    return em.createQuery(allGamesForGivenPlatfrom).getResultList();
}
Example 8
Project: BatooJPA-master  File: SimpleCriteriaTest.java View source code
/**
	 * 
	 * @since 2.0.0
	 */
@Test
public void testAssociationJoin() {
    this.persist(this.person());
    this.persist(this.person());
    this.commit();
    this.close();
    final CriteriaBuilderImpl cb = this.em().getCriteriaBuilder();
    final CriteriaQueryImpl<Address> q = cb.createQuery(Address.class);
    final RootImpl<Person> r = q.from(Person.class);
    final Join<Person, Address> a = r.join("addresses");
    a.fetch("person");
    a.fetch("country");
    q.select(a);
    final List<Address> resultList = this.em().createQuery(q).getResultList();
    Assert.assertEquals(6, resultList.size());
}
Example 9
Project: clinic-softacad-master  File: AbstractFromImpl.java View source code
@Override
@SuppressWarnings({ "unchecked" })
public <X, Y> Join<X, Y> join(String attributeName, JoinType jt) {
    if (!canBeJoinSource()) {
        throw illegalJoin();
    }
    if (jt.equals(JoinType.RIGHT)) {
        throw new UnsupportedOperationException("RIGHT JOIN not supported");
    }
    final Attribute<X, ?> attribute = (Attribute<X, ?>) locateAttribute(attributeName);
    if (attribute.isCollection()) {
        final PluralAttribute pluralAttribute = (PluralAttribute) attribute;
        if (PluralAttribute.CollectionType.COLLECTION.equals(pluralAttribute.getCollectionType())) {
            return (Join<X, Y>) join((CollectionAttribute) attribute, jt);
        } else if (PluralAttribute.CollectionType.LIST.equals(pluralAttribute.getCollectionType())) {
            return (Join<X, Y>) join((ListAttribute) attribute, jt);
        } else if (PluralAttribute.CollectionType.SET.equals(pluralAttribute.getCollectionType())) {
            return (Join<X, Y>) join((SetAttribute) attribute, jt);
        } else {
            return (Join<X, Y>) join((MapAttribute) attribute, jt);
        }
    } else {
        return (Join<X, Y>) join((SingularAttribute) attribute, jt);
    }
}
Example 10
Project: eclipselink.runtime-master  File: CriteriaBuilderImpl.java View source code
@Override
public <X, T, V extends T> Join<X, V> treat(Join<X, T> join, Class<V> type) {
    JoinImpl parentJoin = (JoinImpl) join;
    JoinImpl joinImpl = new JoinImpl<X, V>(parentJoin, this.metamodel.managedType(type), this.metamodel, type, parentJoin.currentNode.treat(type), parentJoin.getModel(), parentJoin.getJoinType());
    parentJoin.joins.add(joinImpl);
    joinImpl.isJoin = parentJoin.isJoin;
    parentJoin.isJoin = false;
    return joinImpl;
}
Example 11
Project: hibernate-core-ogm-master  File: AbstractFromImpl.java View source code
/**
	 * {@inheritDoc}
	 */
@SuppressWarnings({ "unchecked" })
public <X, Y> Join<X, Y> join(String attributeName, JoinType jt) {
    if (!canBeJoinSource()) {
        throw illegalJoin();
    }
    if (jt.equals(JoinType.RIGHT)) {
        throw new UnsupportedOperationException("RIGHT JOIN not supported");
    }
    final Attribute<X, ?> attribute = (Attribute<X, ?>) locateAttribute(attributeName);
    if (attribute.isCollection()) {
        final PluralAttribute pluralAttribute = (PluralAttribute) attribute;
        if (PluralAttribute.CollectionType.COLLECTION.equals(pluralAttribute.getCollectionType())) {
            return (Join<X, Y>) join((CollectionAttribute) attribute, jt);
        } else if (PluralAttribute.CollectionType.LIST.equals(pluralAttribute.getCollectionType())) {
            return (Join<X, Y>) join((ListAttribute) attribute, jt);
        } else if (PluralAttribute.CollectionType.SET.equals(pluralAttribute.getCollectionType())) {
            return (Join<X, Y>) join((SetAttribute) attribute, jt);
        } else {
            return (Join<X, Y>) join((MapAttribute) attribute, jt);
        }
    } else {
        return (Join<X, Y>) join((SingularAttribute) attribute, jt);
    }
}
Example 12
Project: pyramus-master  File: StudentDAO.java View source code
public List<Student> listBy(String email, List<StudentGroup> groups, Boolean archived, Integer firstResult, Integer maxResults) {
    EntityManager entityManager = getEntityManager();
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Student> criteria = criteriaBuilder.createQuery(Student.class);
    Root<Student> root = criteria.from(Student.class);
    Join<Student, ContactInfo> contactInfoJoin = root.join(Student_.contactInfo);
    List<Predicate> predicates = new ArrayList<>();
    if (StringUtils.isNotBlank(email)) {
        ListJoin<ContactInfo, Email> emailJoin = contactInfoJoin.join(ContactInfo_.emails);
        predicates.add(criteriaBuilder.equal(emailJoin.get(Email_.address), email));
    }
    if (archived != null) {
        predicates.add(criteriaBuilder.equal(root.get(Student_.archived), archived));
    }
    if (groups != null) {
        Subquery<Student> subquery = criteria.subquery(Student.class);
        Root<StudentGroupStudent> studentGroup = subquery.from(StudentGroupStudent.class);
        subquery.select(studentGroup.get(StudentGroupStudent_.student));
        subquery.where(studentGroup.get(StudentGroupStudent_.studentGroup).in(groups));
        predicates.add(root.in(subquery));
    }
    criteria.select(root);
    if (!predicates.isEmpty()) {
        criteria.where(criteriaBuilder.and(predicates.toArray(new Predicate[0])));
    }
    TypedQuery<Student> query = entityManager.createQuery(criteria);
    if (firstResult != null) {
        query.setFirstResult(firstResult);
    }
    if (maxResults != null) {
        query.setMaxResults(maxResults);
    }
    return query.getResultList();
}
Example 13
Project: BikeMan-master  File: TransactionRepositoryImpl.java View source code
@SuppressWarnings("unchecked")
private CriteriaQuery<ViewTransactionDTO> getTransactionQuery(CriteriaBuilder builder, FindType findType, CustomerType customerType, Long pedelecId, String login) {
    CriteriaQuery<ViewTransactionDTO> criteria = builder.createQuery(ViewTransactionDTO.class);
    Root<Transaction> transaction = criteria.from(Transaction.class);
    Join<Transaction, Pedelec> pedelec = transaction.join(Transaction_.pedelec, JoinType.LEFT);
    Join<Transaction, StationSlot> fromStationSlot = transaction.join(Transaction_.fromSlot, JoinType.LEFT);
    Join<StationSlot, Station> fromStation = fromStationSlot.join(StationSlot_.station, JoinType.LEFT);
    Join<Transaction, CardAccount> cardAccount = transaction.join(Transaction_.cardAccount, JoinType.LEFT);
    Join user = cardAccount.join(CardAccount_.user, JoinType.LEFT);
    Join<Transaction, StationSlot> toStationSlot = transaction.join(Transaction_.toSlot, JoinType.LEFT);
    Join<StationSlot, Station> toStation = toStationSlot.join(StationSlot_.station, JoinType.LEFT);
    // -------------------------------------------------------------------------
    // Customer type decisions
    // -------------------------------------------------------------------------
    Selection<ViewTransactionDTO> selection = null;
    switch(customerType) {
        case MAJOR_CUSTOMER:
            selection = builder.construct(ViewTransactionDTO.class, transaction.get(Transaction_.transactionId), transaction.get(Transaction_.startDateTime), transaction.get(Transaction_.endDateTime), fromStation.get(Station_.stationId), fromStation.get(Station_.name), fromStationSlot.get(StationSlot_.stationSlotPosition), toStation.get(Station_.stationId), toStation.get(Station_.name), toStationSlot.get(StationSlot_.stationSlotPosition), cardAccount.get(CardAccount_.cardId), user.get(MajorCustomer_.name), pedelec.get(Pedelec_.pedelecId), pedelec.get(Pedelec_.manufacturerId));
            break;
        case FLEET_MANAGER:
            selection = builder.construct(ViewTransactionDTO.class, user.get(Manager_.login), transaction.get(Transaction_.transactionId), transaction.get(Transaction_.startDateTime), transaction.get(Transaction_.endDateTime), fromStation.get(Station_.stationId), fromStation.get(Station_.name), fromStationSlot.get(StationSlot_.stationSlotPosition), toStation.get(Station_.stationId), toStation.get(Station_.name), toStationSlot.get(StationSlot_.stationSlotPosition), cardAccount.get(CardAccount_.cardId), pedelec.get(Pedelec_.pedelecId), pedelec.get(Pedelec_.manufacturerId));
            break;
        case CUSTOMER:
            selection = builder.construct(ViewTransactionDTO.class, transaction.get(Transaction_.transactionId), transaction.get(Transaction_.startDateTime), transaction.get(Transaction_.endDateTime), fromStation.get(Station_.stationId), fromStation.get(Station_.name), fromStationSlot.get(StationSlot_.stationSlotPosition), toStation.get(Station_.stationId), toStation.get(Station_.name), toStationSlot.get(StationSlot_.stationSlotPosition), cardAccount.get(CardAccount_.cardId), user.get(Customer_.customerId), user.get(Customer_.firstname), user.get(Customer_.lastname), pedelec.get(Pedelec_.pedelecId), pedelec.get(Pedelec_.manufacturerId));
            break;
    }
    criteria.select(selection).orderBy(builder.desc(transaction.get(Transaction_.endDateTime)));
    // -------------------------------------------------------------------------
    // Find type decisions
    // -------------------------------------------------------------------------
    Predicate findPredicate = builder.and();
    switch(findType) {
        case ALL:
            break;
        case CLOSED:
            findPredicate = builder.and(builder.isNotNull(transaction.get(Transaction_.toSlot)), builder.isNotNull(transaction.get(Transaction_.endDateTime)));
            break;
        case OPEN:
            findPredicate = builder.and(builder.isNull(transaction.get(Transaction_.toSlot)), builder.isNull(transaction.get(Transaction_.endDateTime)));
            break;
        case BY_PEDELEC_ID:
            findPredicate = builder.equal(pedelec.get(Pedelec_.pedelecId), pedelecId);
            break;
        case BY_LOGIN:
            findPredicate = builder.equal(user.get(User_.login), login);
            break;
    }
    return criteria.where(builder.and(builder.equal(cardAccount.get(CardAccount_.ownerType), customerType), findPredicate));
}
Example 14
Project: jpa-cert-master  File: EmployeeService.java View source code
public List<Object[]> findMaxNumCertificatesByBranch_criteria() {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Object[]> query = cb.createQuery(Object[].class);
    Root<Branch> branch = query.from(Branch.class);
    Join<Branch, Employee> employee = branch.join("employees");
    Join<Employee, Certificate> cert = employee.join("certificates");
    Subquery<Long> sq = query.subquery(Long.class);
    Root<Employee> emp2 = sq.from(Employee.class);
    sq.select(cb.count(emp2.get("certificates"))).where(cb.isMember(emp2, branch.<List<Employee>>get("employees"))).groupBy(emp2);
    query.multiselect(branch, cb.count(cert)).distinct(true).groupBy(branch, employee).having(cb.greaterThanOrEqualTo(cb.count(cert), cb.all(sq))).orderBy(cb.asc(branch.get("id")));
    return em.createQuery(query).getResultList();
}
Example 15
Project: muikku-master  File: CommunicatorMessageDAO.java View source code
private List<CommunicatorThreadBasicInfo> listUserThreadBasicInfos(UserEntity userEntity, CommunicatorFolderType type, CommunicatorLabel label) {
    EntityManager entityManager = getEntityManager();
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<CommunicatorThreadBasicInfo> criteria = criteriaBuilder.createQuery(CommunicatorThreadBasicInfo.class);
    switch(type) {
        case UNREAD:
            {
                Root<CommunicatorMessageRecipient> root = criteria.from(CommunicatorMessageRecipient.class);
                Join<CommunicatorMessageRecipient, CommunicatorMessage> messageJoin = root.join(CommunicatorMessageRecipient_.communicatorMessage);
                criteria.multiselect(messageJoin.get(CommunicatorMessage_.communicatorMessageId), criteriaBuilder.greatest(messageJoin.get(CommunicatorMessage_.created)));
                criteria.where(criteriaBuilder.and(criteriaBuilder.equal(root.get(CommunicatorMessageRecipient_.recipient), userEntity.getId()), criteriaBuilder.equal(root.get(CommunicatorMessageRecipient_.readByReceiver), Boolean.FALSE), criteriaBuilder.equal(root.get(CommunicatorMessageRecipient_.trashedByReceiver), Boolean.FALSE), criteriaBuilder.equal(root.get(CommunicatorMessageRecipient_.archivedByReceiver), Boolean.FALSE)));
                criteria.groupBy(messageJoin.get(CommunicatorMessage_.communicatorMessageId));
            }
            break;
        case LABEL:
            {
                Root<CommunicatorMessageRecipient> root = criteria.from(CommunicatorMessageRecipient.class);
                Join<CommunicatorMessageRecipient, CommunicatorMessage> messageJoin = root.join(CommunicatorMessageRecipient_.communicatorMessage);
                Join<CommunicatorMessage, CommunicatorMessageId> threadJoin = messageJoin.join(CommunicatorMessage_.communicatorMessageId);
                criteria.multiselect(messageJoin.get(CommunicatorMessage_.communicatorMessageId), criteriaBuilder.greatest(messageJoin.get(CommunicatorMessage_.created)));
                Root<CommunicatorMessageIdLabel> labelRoot = criteria.from(CommunicatorMessageIdLabel.class);
                criteria.where(criteriaBuilder.and(criteriaBuilder.equal(root.get(CommunicatorMessageRecipient_.recipient), userEntity.getId()), criteriaBuilder.equal(root.get(CommunicatorMessageRecipient_.trashedByReceiver), Boolean.FALSE), criteriaBuilder.equal(root.get(CommunicatorMessageRecipient_.archivedByReceiver), Boolean.FALSE), threadJoin.in(labelRoot.get(CommunicatorMessageIdLabel_.communicatorMessageId)), criteriaBuilder.equal(labelRoot.get(CommunicatorMessageIdLabel_.label), label)));
                criteria.groupBy(messageJoin.get(CommunicatorMessage_.communicatorMessageId));
            }
            break;
        case SENT:
            {
                Root<CommunicatorMessage> root = criteria.from(CommunicatorMessage.class);
                criteria.multiselect(root.get(CommunicatorMessage_.communicatorMessageId), criteriaBuilder.greatest(root.get(CommunicatorMessage_.created)));
                criteria.where(criteriaBuilder.and(criteriaBuilder.equal(root.get(CommunicatorMessage_.sender), userEntity.getId()), criteriaBuilder.equal(root.get(CommunicatorMessage_.archivedBySender), Boolean.FALSE), criteriaBuilder.equal(root.get(CommunicatorMessage_.trashedBySender), Boolean.FALSE)));
                criteria.groupBy(root.get(CommunicatorMessage_.communicatorMessageId));
            }
            break;
        case INBOX:
        case TRASH:
            Root<CommunicatorMessageRecipient> root = criteria.from(CommunicatorMessageRecipient.class);
            Join<CommunicatorMessageRecipient, CommunicatorMessage> messageJoin = root.join(CommunicatorMessageRecipient_.communicatorMessage);
            criteria.multiselect(messageJoin.get(CommunicatorMessage_.communicatorMessageId), criteriaBuilder.greatest(messageJoin.get(CommunicatorMessage_.created)));
            criteria.where(criteriaBuilder.and(criteriaBuilder.equal(root.get(CommunicatorMessageRecipient_.recipient), userEntity.getId()), criteriaBuilder.equal(root.get(CommunicatorMessageRecipient_.trashedByReceiver), type == CommunicatorFolderType.TRASH), criteriaBuilder.equal(root.get(CommunicatorMessageRecipient_.archivedByReceiver), Boolean.FALSE)));
            criteria.groupBy(messageJoin.get(CommunicatorMessage_.communicatorMessageId));
            break;
    }
    List<CommunicatorThreadBasicInfo> threads = entityManager.createQuery(criteria).getResultList();
    Collections.sort(threads, new Comparator<CommunicatorThreadBasicInfo>() {

        @Override
        public int compare(CommunicatorThreadBasicInfo o1, CommunicatorThreadBasicInfo o2) {
            return o2.getLatestThread().compareTo(o1.getLatestThread());
        }
    });
    return threads;
}
Example 16
Project: query-master  File: JoinBuilder.java View source code
@Override
public List<Predicate> build(CriteriaBuilder builder, Path<P> path) {
    Join join = null;
    if (singular != null) {
        join = joinSingular((From) path);
    } else if (list != null) {
        join = joinList((From) path);
    } else if (collection != null) {
        join = joinCollection((From) path);
    } else if (set != null) {
        join = joinSet((From) path);
    } else {
        join = joinMap((From) path);
    }
    return criteria.predicates(builder, join);
}
Example 17
Project: sigmah-master  File: ContactHibernateDAO.java View source code
@Override
public List<Contact> findContactsByTypeAndContactModels(Integer organizationId, ContactModelType type, Set<Integer> contactModelIds, boolean onlyWithoutUser, boolean withEmailNotNull, Set<Integer> orgUnitsIds) {
    // Too much nullable parameters, let's use criteria query builder to ease the query creation
    // and to avoid using dangerous string concatenation
    CriteriaBuilder criteriaBuilder = em().getCriteriaBuilder();
    CriteriaQuery<Contact> criteriaQuery = criteriaBuilder.createQuery(Contact.class);
    Root<Contact> contactRoot = criteriaQuery.from(Contact.class);
    Join<Object, Object> contactModelJoin = contactRoot.join("contactModel", JoinType.INNER);
    Join<Object, Object> organizationJoin = contactModelJoin.join("organization", JoinType.INNER);
    Join<Object, Object> userJoin = contactRoot.join("user", JoinType.LEFT);
    Join<Object, Object> mainOrgUnitJoin = contactRoot.join("mainOrgUnit", JoinType.LEFT);
    Join<Object, Object> secondaryOrgUnitJoin = contactRoot.join("secondaryOrgUnits", JoinType.LEFT);
    Join<Object, Object> userOrgUnitsJoin = userJoin.join("orgUnitsWithProfiles", JoinType.LEFT);
    Join<Object, Object> organizationOrgUnitsJoin = contactRoot.join("organization", JoinType.LEFT).join("orgUnit", JoinType.LEFT);
    List<Predicate> predicates = new ArrayList<>();
    predicates.add(criteriaBuilder.equal(organizationJoin.get("id"), organizationId));
    if (type != null) {
        predicates.add(criteriaBuilder.equal(contactModelJoin.get("type"), type));
    }
    if (contactModelIds != null && !contactModelIds.isEmpty()) {
        predicates.add(contactModelJoin.get("id").in(contactModelIds));
    }
    if (onlyWithoutUser) {
        predicates.add(userJoin.get("id").isNull());
    }
    if (withEmailNotNull) {
        predicates.add(criteriaBuilder.or(contactRoot.get("email").isNotNull(), userJoin.get("email").isNotNull()));
    }
    if (orgUnitsIds != null && !orgUnitsIds.isEmpty()) {
        predicates.add(criteriaBuilder.or(criteriaBuilder.or(mainOrgUnitJoin.get("id").in(orgUnitsIds), secondaryOrgUnitJoin.get("id").in(orgUnitsIds)), criteriaBuilder.or(userOrgUnitsJoin.get("orgUnit").get("id").in(orgUnitsIds), organizationOrgUnitsJoin.get("id").in(orgUnitsIds))));
    }
    criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()]));
    criteriaQuery.select(contactRoot);
    criteriaQuery.orderBy(criteriaBuilder.asc(contactRoot.get("name")));
    return em().createQuery(criteriaQuery).getResultList();
}
Example 18
Project: trade-manager-master  File: TradingdayHome.java View source code
/**
	 * Method findTradestrategyByDate.
	 * 
	 * @param open
	 *            Date
	 * @return List<Tradestrategy>
	 */
private List<Tradestrategy> findTradestrategyByIdTradingday(Integer idTradingday) {
    try {
        EntityManager entityManager = EntityManagerHelper.getEntityManager();
        CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        CriteriaQuery<Tradestrategy> query = builder.createQuery(Tradestrategy.class);
        Root<Tradestrategy> from = query.from(Tradestrategy.class);
        query.select(from);
        List<Predicate> predicates = new ArrayList<Predicate>();
        if (null != idTradingday) {
            Join<Tradestrategy, Tradingday> tradingday = from.join("tradingday");
            Predicate predicate = builder.equal(tradingday.get("idTradingDay"), idTradingday);
            predicates.add(predicate);
        }
        query.where(predicates.toArray(new Predicate[] {}));
        TypedQuery<Tradestrategy> typedQuery = entityManager.createQuery(query);
        List<Tradestrategy> items = typedQuery.getResultList();
        return items;
    } catch (Exception re) {
        throw re;
    }
}
Example 19
Project: curso-javaee-primefaces-master  File: Pedidos.java View source code
public int quantidadeFiltrados(PedidoFilter filtro) {
    CriteriaBuilder builder = manager.getCriteriaBuilder();
    CriteriaQuery<Long> criteriaQuery = builder.createQuery(Long.class);
    Root<Pedido> pedidoRoot = criteriaQuery.from(Pedido.class);
    Join<Pedido, Cliente> clienteJoin = pedidoRoot.join("cliente", JoinType.INNER);
    Join<Pedido, Cliente> vendedorJoin = pedidoRoot.join("vendedor", JoinType.INNER);
    List<Predicate> predicates = criarPredicatesParaFiltro(filtro, pedidoRoot, clienteJoin, vendedorJoin);
    criteriaQuery.select(builder.count(pedidoRoot));
    criteriaQuery.where(predicates.toArray(new Predicate[0]));
    TypedQuery<Long> query = manager.createQuery(criteriaQuery);
    return query.getSingleResult().intValue();
}
Example 20
Project: deltaspike-master  File: JoinBuilder.java View source code
@Override
public List<Predicate> build(CriteriaBuilder builder, Path<P> path) {
    Join join = null;
    if (singular != null) {
        join = joinSingular((From) path);
    } else if (list != null) {
        join = joinList((From) path);
    } else if (collection != null) {
        join = joinCollection((From) path);
    } else if (set != null) {
        join = joinSet((From) path);
    } else {
        join = joinMap((From) path);
    }
    return criteria.predicates(builder, join);
}
Example 21
Project: genie-master  File: JpaClusterSpecs.java View source code
/**
     * Get all the clusters given the specified parameters.
     *
     * @param clusterCriteria The cluster criteria
     * @param commandCriteria The command Criteria
     * @return The specification
     */
public static Specification<ClusterEntity> findByClusterAndCommandCriteria(final ClusterCriteria clusterCriteria, final Set<String> commandCriteria) {
    return (final Root<ClusterEntity> root, final CriteriaQuery<?> cq, final CriteriaBuilder cb) -> {
        final List<Predicate> predicates = new ArrayList<>();
        final Join<ClusterEntity, CommandEntity> commands = root.join(ClusterEntity_.commands);
        cq.distinct(true);
        predicates.add(cb.equal(root.get(ClusterEntity_.status), ClusterStatus.UP));
        if (clusterCriteria != null && clusterCriteria.getTags() != null && !clusterCriteria.getTags().isEmpty()) {
            predicates.add(cb.like(root.get(ClusterEntity_.tags), JpaSpecificationUtils.getTagLikeString(clusterCriteria.getTags())));
        }
        predicates.add(cb.equal(commands.get(CommandEntity_.status), CommandStatus.ACTIVE));
        if (commandCriteria != null && !commandCriteria.isEmpty()) {
            predicates.add(cb.like(commands.get(CommandEntity_.tags), JpaSpecificationUtils.getTagLikeString(commandCriteria)));
        }
        return cb.and(predicates.toArray(new Predicate[predicates.size()]));
    };
}
Example 22
Project: jdal-master  File: TestJpaDao.java View source code
@Test
@Transactional
public void testCountCriteria() {
    EntityManager em = bookDao.getEntityManager();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Book> criteria = cb.createQuery(Book.class);
    Root<Book> root = criteria.from(Book.class);
    Join<Book, Author> join = root.join("author");
    criteria.where(join.isNotNull());
    CriteriaQuery<Long> countCriteria = JpaUtils.countCriteria(em, criteria);
    Long result = em.createQuery(countCriteria).getSingleResult();
    log.debug("Count: " + result);
}
Example 23
Project: jpasearch-master  File: JpaUtil.java View source code
@SuppressWarnings("unchecked")
public <E, F> Path<F> getPath(Root<E> root, List<Attribute<?, ?>> attributes) {
    Path<?> path = root;
    for (Attribute<?, ?> attribute : attributes) {
        boolean found = false;
        if (path instanceof FetchParent) {
            for (Fetch<E, ?> fetch : ((FetchParent<?, E>) path).getFetches()) {
                if (attribute.getName().equals(fetch.getAttribute().getName()) && (fetch instanceof Join<?, ?>)) {
                    path = (Join<E, ?>) fetch;
                    found = true;
                    break;
                }
            }
        }
        if (!found) {
            if ((attributes.indexOf(attribute) != (attributes.size() - 1)) && (attribute instanceof Bindable) && Identifiable.class.isAssignableFrom(((Bindable<?>) attribute).getBindableJavaType()) && (path instanceof From)) {
                path = ((From<?, ?>) path).join(attribute.getName(), JoinType.LEFT);
            } else {
                path = path.get(attribute.getName());
            }
        }
    }
    return (Path<F>) path;
}
Example 24
Project: uPortal-master  File: JpaBaseAggregationDao.java View source code
@Override
public CriteriaQuery<T> apply(CriteriaBuilder cb) {
    final CriteriaQuery<T> criteriaQuery = cb.createQuery(aggregationEntityType);
    final Root<T> ba = criteriaQuery.from(aggregationEntityType);
    final Join<T, DateDimensionImpl> dd = ba.join(BaseAggregationImpl_.dateDimension, JoinType.LEFT);
    final Join<T, TimeDimensionImpl> td = ba.join(BaseAggregationImpl_.timeDimension, JoinType.LEFT);
    final List<Predicate> keyPredicates = new ArrayList<Predicate>();
    keyPredicates.add(//Restrict results by outer date range
    cb.and(cb.greaterThanOrEqualTo(dd.get(DateDimensionImpl_.date), startDate), cb.lessThan(dd.get(DateDimensionImpl_.date), endPlusOneDate)));
    keyPredicates.add(//Restrict start of range by time as well
    cb.or(cb.greaterThan(dd.get(DateDimensionImpl_.date), startDate), cb.greaterThanOrEqualTo(td.get(TimeDimensionImpl_.time), startTime)));
    keyPredicates.add(//Restrict end of range by time as well
    cb.or(cb.lessThan(dd.get(DateDimensionImpl_.date), endDate), cb.lessThan(td.get(TimeDimensionImpl_.time), endTime)));
    keyPredicates.add(cb.equal(ba.get(BaseAggregationImpl_.interval), intervalParameter));
    keyPredicates.add(ba.get(BaseAggregationImpl_.aggregatedGroup).in(aggregatedGroupsParameter));
    addAggregationSpecificKeyPredicate(cb, ba, keyPredicates);
    criteriaQuery.select(ba);
    criteriaQuery.where(keyPredicates.toArray(new Predicate[keyPredicates.size()]));
    criteriaQuery.orderBy(cb.desc(dd.get(DateDimensionImpl_.date)), cb.desc(td.get(TimeDimensionImpl_.time)));
    return criteriaQuery;
}
Example 25
Project: BusinessManager-master  File: GenericDaoImpl.java View source code
public List<T> findByAssignedEntity(ListAttribute<T, ?> listAttribute, Long entityId) {
    CriteriaBuilder queryBuilder = getEntityManager().getCriteriaBuilder();
    CriteriaQuery<T> criteriaQuery = queryBuilder.createQuery(getPersistenceClass());
    Root<T> rootQuery = criteriaQuery.from(getPersistenceClass());
    CriteriaQuery<T> select = criteriaQuery.select(rootQuery);
    Join<T, ?> memberJoin = rootQuery.join(listAttribute);
    Path<?> nameField = memberJoin.get("id");
    Predicate nameEquals = queryBuilder.equal(nameField, entityId);
    criteriaQuery.where(nameEquals);
    TypedQuery<T> typedQuery = getEntityManager().createQuery(select);
    return typedQuery.getResultList();
}
Example 26
Project: che-master  File: JpaRecipeDao.java View source code
@Override
@Transactional
public List<RecipeImpl> search(String user, List<String> tags, String type, int skipCount, int maxItems) throws ServerException {
    try {
        final EntityManager manager = managerProvider.get();
        final CriteriaBuilder cb = manager.getCriteriaBuilder();
        final CriteriaQuery<RecipeImpl> query = cb.createQuery(RecipeImpl.class);
        final Root<RecipeImpl> fromRecipe = query.from(RecipeImpl.class);
        final ParameterExpression<String> typeParam = cb.parameter(String.class, "recipeType");
        final Predicate checkType = cb.or(cb.isNull(typeParam), cb.equal(fromRecipe.get("type"), typeParam));
        final TypedQuery<RecipeImpl> typedQuery;
        if (tags != null && !tags.isEmpty()) {
            final Join<RecipeImpl, String> tag = fromRecipe.join("tags");
            query.select(cb.construct(RecipeImpl.class, tag.getParent())).where(cb.and(checkType, tag.in(tags))).groupBy(fromRecipe.get("id")).having(cb.equal(cb.count(tag), tags.size()));
            typedQuery = manager.createQuery(query).setParameter("tags", tags);
        } else {
            typedQuery = manager.createQuery(query.where(checkType));
        }
        return typedQuery.setParameter("recipeType", type).setFirstResult(skipCount).setMaxResults(maxItems).getResultList();
    } catch (RuntimeException ex) {
        throw new ServerException(ex.getLocalizedMessage(), ex);
    }
}
Example 27
Project: DevTools-master  File: JpaRecipeDao.java View source code
@Override
@Transactional
public List<RecipeImpl> search(String user, List<String> tags, String type, int skipCount, int maxItems) throws ServerException {
    try {
        final EntityManager manager = managerProvider.get();
        final CriteriaBuilder cb = manager.getCriteriaBuilder();
        final CriteriaQuery<RecipeImpl> query = cb.createQuery(RecipeImpl.class);
        final Root<RecipeImpl> fromRecipe = query.from(RecipeImpl.class);
        final ParameterExpression<String> typeParam = cb.parameter(String.class, "recipeType");
        final Predicate checkType = cb.or(cb.isNull(typeParam), cb.equal(fromRecipe.get("type"), typeParam));
        final TypedQuery<RecipeImpl> typedQuery;
        if (tags != null && !tags.isEmpty()) {
            final Join<RecipeImpl, String> tag = fromRecipe.join("tags");
            query.select(cb.construct(RecipeImpl.class, tag.getParent())).where(cb.and(checkType, tag.in(tags))).groupBy(fromRecipe.get("id")).having(cb.equal(cb.count(tag), tags.size()));
            typedQuery = manager.createQuery(query).setParameter("tags", tags);
        } else {
            typedQuery = manager.createQuery(query.where(checkType));
        }
        return typedQuery.setParameter("recipeType", type).setFirstResult(skipCount).setMaxResults(maxItems).getResultList();
    } catch (RuntimeException ex) {
        throw new ServerException(ex.getLocalizedMessage(), ex);
    }
}
Example 28
Project: idnadrev-master  File: NextTaskChooser.java View source code
protected List<Task> getAllPossibleTasks(int minutes, String selectedContext) {
    List<Task> retval = PersistentWork.wrap(() -> {
        List<Task> tasks = PersistentWork.from(Task.class, ( root,  query,  builder) -> {
            ArrayList<Predicate> predicates = new ArrayList<>();
            if (selectedContext != null) {
                Join<Task, Context> join = root.join(KEY_CONTEXT);
                join.on(builder.equal(join.get(KEY_CONTEXT_NAME), selectedContext));
            } else {
                predicates.add(builder.isNull(root.get(KEY_CONTEXT)));
            }
            Path<Object> state = root.get(KEY_STATE);
            predicates.add(builder.notEqual(state, TaskState.LATER));
            predicates.add(builder.notEqual(state, TaskState.DELEGATED));
            predicates.add(builder.isNull(root.get(KEY_FINISHTIME)));
            query.where(predicates.toArray(new Predicate[predicates.size()]));
        }, null);
        return //super ugly, need to evict to save heap
        tasks.stream().sorted(//
        Comparator.comparing( c -> c.getEstimatedTime().toMinutes() - c.getSpentMinutes())).filter( t -> {
            long timeRemaining = t.getRemainingTime().toMinutes();
            log.info("Remaining time: {}", timeRemaining);
            return timeRemaining < minutes && timeRemaining > 2;
        }).collect(//
        Collectors.toList());
    });
    return retval;
}
Example 29
Project: olog-service-master  File: JPAUtilTest.java View source code
/**
     * Copy Joins
     *
     * @param from source Join
     * @param to destination Join
     */
public static void copyJoins(From<?, ?> from, From<?, ?> to) {
    for (Join<?, ?> j : from.getJoins()) {
        Join<?, ?> toJoin = to.join(j.getAttribute().getName(), j.getJoinType());
        toJoin.alias(getOrCreateAlias(j));
        copyJoins(j, toJoin);
    }
    for (Fetch<?, ?> f : from.getFetches()) {
        Fetch<?, ?> toFetch = to.fetch(f.getAttribute().getName());
        copyFetches(f, toFetch);
    }
}
Example 30
Project: openjpa-master  File: TestTypesafeCriteria.java View source code
public void testExpressions() {
    String jpql = "SELECT o.quantity, o.totalCost*1.08, " + "a.zipCode FROM Customer c JOIN c.orders o JOIN c.address a " + "WHERE a.state = 'CA' AND a.county = 'Santa Clara'";
    CriteriaQuery<?> q = cb.createQuery();
    Root<Customer> cust = q.from(Customer.class);
    SetJoin<Customer, Order> order = cust.joinSet("orders");
    Join<Customer, Address> address = cust.join("address");
    q.where(cb.equal(address.get("state"), "CA"), cb.equal(address.get("county"), "Santa Clara"));
    Expression<Double> taxedCost = cb.prod(order.get(Order_.totalCost), 1.08);
    q.multiselect(order.get("quantity"), taxedCost, address.get("zipCode"));
    assertEquivalence(q, jpql);
}
Example 31
Project: resource-server-master  File: UserQueryField.java View source code
@SuppressWarnings("unchecked")
protected Join<UserEntity, NameEntity> createOrGetJoinForName(final Root<UserEntity> root) {
    for (final Join<UserEntity, ?> currentJoin : root.getJoins()) {
        if (currentJoin.getAlias() != null && currentJoin.getAlias().equals(JOIN_ALIAS_FOR_NAME)) {
            return (Join<UserEntity, NameEntity>) currentJoin;
        }
    }
    Join<UserEntity, NameEntity> join = root.join(UserEntity_.name, JoinType.LEFT);
    join.alias(JOIN_ALIAS_FOR_NAME);
    return join;
}
Example 32
Project: cxf-master  File: AbstractJPATypedQueryVisitor.java View source code
private Path<?> getNextPath(Path<?> element, String name, String postName, ClassValue cv, CollectionCheckInfo collSize) {
    final boolean isCollectionOrJoin = collSize == null && (cv.isCollection(name) || isJoinProperty(name) || existingCollectionInPostName(cv, postName)) && (element == root || element instanceof Join);
    if (isCollectionOrJoin) {
        final Path<?> path = getExistingJoinProperty((From<?, ?>) element, name);
        if (path != null) {
            return path;
        } else {
            return element == root ? root.join(name) : ((Join<?, ?>) element).join(name);
        }
    } else {
        return element.get(name);
    }
}
Example 33
Project: jbpm-master  File: TaskSummaryQueryCriteriaUtil.java View source code
/*
     * (non-Javadoc)
     * @see org.jbpm.query.jpa.impl.QueryCriteriaUtil#getEntityField(javax.persistence.criteria.CriteriaQuery, java.lang.Class, java.lang.String)
     */
@Override
protected <T> Expression getEntityField(CriteriaQuery<T> query, String listId, Attribute attr) {
    if (attr == null) {
        return null;
    }
    Root<TaskImpl> taskRoot = null;
    Join<TaskImpl, TaskDataImpl> taskDataJoin = null;
    Join<TaskImpl, PeopleAssignmentsImpl> peopAssignJoin = null;
    for (Root root : query.getRoots()) {
        if (TaskImpl.class.equals(root.getJavaType())) {
            taskRoot = (Root<TaskImpl>) root;
            for (Join<TaskImpl, ?> join : taskRoot.getJoins()) {
                if (TaskDataImpl.class.equals(join.getJavaType())) {
                    taskDataJoin = (Join<TaskImpl, TaskDataImpl>) join;
                } else if (PeopleAssignmentsImpl.class.equals(join.getJavaType())) {
                    peopAssignJoin = (Join<TaskImpl, PeopleAssignmentsImpl>) join;
                }
            }
        }
    }
    assert taskRoot != null : "Unable to find TaskImpl Root in query!";
    if (taskDataJoin == null) {
        taskDataJoin = taskRoot.join(TaskImpl_.taskData);
    }
    assert taskDataJoin != null : "Unable to find TaskDataImpl Join in query!";
    return taskImplSpecificGetEntityField(query, taskRoot, taskDataJoin, peopAssignJoin, listId, attr);
}
Example 34
Project: sislegis-app-master  File: ElaboracaoNormativaServiceEjb.java View source code
@SuppressWarnings("unchecked")
@Override
public List<ElaboracaoNormativa> buscaPorParametros(Map<String, Object> mapaCampos) {
    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
    CriteriaQuery<ElaboracaoNormativa> cq = cb.createQuery(ElaboracaoNormativa.class);
    Root<ElaboracaoNormativa> en = cq.from(ElaboracaoNormativa.class);
    Join<ElaboracaoNormativa, Orgao> oen = en.join("origem", JoinType.LEFT);
    Join<ElaboracaoNormativa, Orgao> ca = en.join("coAutor", JoinType.LEFT);
    Join<ElaboracaoNormativa, StatusSidof> ss = en.join("statusSidof", JoinType.LEFT);
    Join<ElaboracaoNormativa, Equipe> eq = en.join("equipe", JoinType.LEFT);
    Join<ElaboracaoNormativa, Usuario> us = en.join("parecerista", JoinType.LEFT);
    cq.select(cb.construct(ElaboracaoNormativa.class, en.get("id"), en.get("tipo"), en.get("subTipo"), en.get("elaboracaoNormativaSituacao"), en.get("elaboracaoNormativaNorma"), en.get("ano"), en.get("numero"), oen.get("nome"), ca.get("nome"), en.get("ementa"), ss.get("descricao"), en.get("identificacao"), eq.get("nome"), us.get("nome"), en.get("nup"), en.get("dataInclusaoSIDOF"), en.get("dataAssinaturaSIDOF"), en.get("ementaManifestacao"), en.get("dataManifestacao"), en.get("normaGeradaAno"), en.get("normaGeradaNumero")));
    List<Predicate> predicates = new ArrayList<Predicate>();
    if (!Objects.isNull(mapaCampos.get("ano")) && !mapaCampos.get("ano").equals("")) {
        Predicate ano = cb.equal(en.get("ano"), mapaCampos.get("ano"));
        predicates.add(ano);
    }
    if (!Objects.isNull(mapaCampos.get("numero")) && !mapaCampos.get("numero").equals("")) {
        Predicate numero = cb.equal(en.get("numero"), mapaCampos.get("numero"));
        predicates.add(numero);
    }
    if (!Objects.isNull(mapaCampos.get("identificacao")) && !mapaCampos.get("identificacao").equals("")) {
        Predicate identificacao = cb.equal(en.get("identificacao"), ElaboracaoNormativaObjeto.get((String) mapaCampos.get("identificacao")));
        predicates.add(identificacao);
    }
    if (!Objects.isNull(mapaCampos.get("distribuicao")) && ((Long) mapaCampos.get("distribuicao")).compareTo(0L) != 0L) {
        Predicate distribuicao = cb.equal(en.get("distribuicao"), mapaCampos.get("distribuicao"));
        predicates.add(distribuicao);
    }
    if (!Objects.isNull(mapaCampos.get("parecerista")) && ((Long) mapaCampos.get("parecerista")).compareTo(0L) != 0L) {
        Predicate parecerista = cb.equal(en.get("parecerista"), mapaCampos.get("parecerista"));
        predicates.add(parecerista);
    }
    if (!Objects.isNull(mapaCampos.get("statusSidof")) && ((Long) mapaCampos.get("statusSidof")).compareTo(0L) != 0L) {
        Predicate statusSidof = cb.equal(ss.get("id"), mapaCampos.get("statusSidof"));
        predicates.add(statusSidof);
    }
    if (!Objects.isNull(mapaCampos.get("elaboracaoNormativaNorma")) && !mapaCampos.get("elaboracaoNormativaNorma").equals("")) {
        Predicate elaboracaoNormativaNorma = cb.equal(en.get("elaboracaoNormativaNorma"), ElaboracaoNormativaNorma.get((String) mapaCampos.get("elaboracaoNormativaNorma")));
        predicates.add(elaboracaoNormativaNorma);
    }
    if (!Objects.isNull(mapaCampos.get("elaboracaoNormativaSituacao")) && !mapaCampos.get("elaboracaoNormativaSituacao").equals("")) {
        Predicate elaboracaoNormativaSituacao = cb.equal(en.get("elaboracaoNormativaSituacao"), ElaboracaoNormativaSituacao.get((String) mapaCampos.get("elaboracaoNormativaSituacao")));
        predicates.add(elaboracaoNormativaSituacao);
    }
    if (!Objects.isNull(mapaCampos.get("tipo")) && !mapaCampos.get("tipo").equals("")) {
        Predicate tipo = cb.equal(en.get("tipo"), ElaboracaoNormativaTipo.get((String) mapaCampos.get("tipo")));
        predicates.add(tipo);
    }
    if (!Objects.isNull(mapaCampos.get("subTipo")) && !mapaCampos.get("subTipo").equals("")) {
        Predicate subTipo = cb.equal(en.get("subTipo"), ElaboracaoNormativaSubTipo.get((String) mapaCampos.get("subTipo")));
        predicates.add(subTipo);
    }
    if (!Objects.isNull(mapaCampos.get("ementa")) && !mapaCampos.get("ementa").equals("")) {
        Predicate ementa = cb.like(en.<String>get("ementa"), mapaCampos.get("ementa").toString());
        predicates.add(ementa);
    }
    if (!Objects.isNull(mapaCampos.get("listaOrigensSelecionadosDropdown")) && !mapaCampos.get("listaOrigensSelecionadosDropdown").equals("")) {
        List<String> lista = SislegisUtil.jsonArrayToList(mapaCampos.get("listaOrigensSelecionadosDropdown").toString());
        if (!lista.isEmpty()) {
            Predicate listaOrigensSelecionadosDropdown = oen.get("id").in(lista);
            predicates.add(listaOrigensSelecionadosDropdown);
        }
    }
    if (!Objects.isNull(mapaCampos.get("listaTagsSelecionadosDropdown")) && !mapaCampos.get("listaTagsSelecionadosDropdown").equals("")) {
        Subquery<TagElaboracaoNormativa> subqueryTags = cq.subquery(TagElaboracaoNormativa.class);
        @SuppressWarnings("rawtypes") Root fromTagElaboracaoNormativa = subqueryTags.from(TagElaboracaoNormativa.class);
        subqueryTags.select(fromTagElaboracaoNormativa.get("elaboracaoNormativa"));
        Join<TagElaboracaoNormativa, Tag> tag = fromTagElaboracaoNormativa.join("tag", JoinType.INNER);
        List<String> lista = SislegisUtil.jsonArrayToList(mapaCampos.get("listaTagsSelecionadosDropdown").toString());
        if (!lista.isEmpty()) {
            subqueryTags.where(tag.get("tag").in(lista));
            predicates.add(en.get("id").in(subqueryTags));
        }
    }
    if (!Objects.isNull(mapaCampos.get("listaCoAutoresSelecionadosDropdown")) && !mapaCampos.get("listaCoAutoresSelecionadosDropdown").equals("")) {
        List<String> lista = SislegisUtil.jsonArrayToList(mapaCampos.get("listaCoAutoresSelecionadosDropdown").toString());
        if (!lista.isEmpty()) {
            Predicate listaCoAutoresSelecionadosDropdown = ca.get("id").in(lista);
            predicates.add(listaCoAutoresSelecionadosDropdown);
        }
    }
    if (!Objects.isNull(mapaCampos.get("nup")) && !mapaCampos.get("nup").equals("")) {
        Predicate nup = cb.like(en.<String>get("nup"), mapaCampos.get("nup").toString());
        predicates.add(nup);
    }
    cq.where(predicates.toArray(new Predicate[] {}));
    Query query = getEntityManager().createQuery(cq);
    List<ElaboracaoNormativa> result = query.getResultList();
    return result;
}
Example 35
Project: blaze-persistence-master  File: InternalQuery.java View source code
public Set<Join<?, ?>> collectCorrelatedJoins() {
    if (!isSubQuery) {
        throw new IllegalStateException("Query is not identified as sub-query");
    }
    final Set<Join<?, ?>> correlatedJoins;
    if (correlationRoots != null) {
        correlatedJoins = new HashSet<Join<?, ?>>();
        for (AbstractFrom<?, ?> correlationRoot : correlationRoots) {
            correlatedJoins.addAll(correlationRoot.getJoins());
        }
    } else {
        correlatedJoins = Collections.emptySet();
    }
    return correlatedJoins;
}
Example 36
Project: jpacontainer-master  File: LocalEntityProvider.java View source code
/**
     * Translates SortBy instances, which possibly contain nested properties
     * (e.g. name.firstName, name.lastName) into Order instances which can be
     * used in a CriteriaQuery.
     * 
     * @param sortBy
     *            the SortBy instance to translate
     * @param swapSortOrder
     *            swaps the specified sort order if true.
     * @param cb
     *            the {@link CriteriaBuilder} to use
     * @param root
     *            the {@link CriteriaQuery} {@link Root} to be used.
     * @return
     */
protected Order translateSortBy(SortBy sortBy, boolean swapSortOrder, CriteriaBuilder cb, Root<T> root) {
    String sortedPropId = sortBy.getPropertyId().toString();
    // First split the id and build a Path.
    String[] idStrings = sortedPropId.split("\\.");
    Path<T> path = null;
    if (idStrings.length > 1 && !isEmbedded(idStrings[0])) {
        // This is a nested property, we need to LEFT JOIN
        path = root.join(idStrings[0], JoinType.LEFT);
        for (int i = 1; i < idStrings.length; i++) {
            if (i < idStrings.length - 1) {
                path = ((Join<?, ?>) path).join(idStrings[i], JoinType.LEFT);
            } else {
                path = path.get(idStrings[i]);
            }
        }
    } else {
        // non-nested or embedded, we can select as usual
        path = AdvancedFilterableSupport.getPropertyPathTyped(root, sortedPropId);
    }
    // Make and return the Order instances.
    if (sortBy.isAscending() != swapSortOrder) {
        return cb.asc(path);
    } else {
        return cb.desc(path);
    }
}
Example 37
Project: molgenis_apps-legacy-master  File: MutationService.java View source code
protected List<Mutation> _findMutations(MutationSearchCriteriaVO criteria) throws DatabaseException {
    if (this.db instanceof JDBCDatabase) {
        Query<Mutation> query = this.db.query(Mutation.class);
        if (criteria.getCdnaPosition() != null)
            query = query.equals(Mutation.CDNA_POSITION, criteria.getCdnaPosition());
        if (criteria.getCodonChangeNumber() != null)
            query = query.equals(Mutation.AA_POSITION, criteria.getCodonChangeNumber());
        if (StringUtils.length(criteria.getConsequence()) > 2)
            query = query.like(Mutation.CONSEQUENCE, criteria.getConsequence() + "%");
        if (criteria.getExonId() != null)
            query = query.equals(Mutation.EXON, criteria.getExonId());
        if (criteria.getExonName() != null)
            query = query.equals(Mutation.EXON_NAME, "Exon " + criteria.getExonName()).or().equals(Mutation.EXON_NAME, "IVS" + criteria.getExonName());
        if (criteria.getExonNumber() != null)
            query = query.equals(Mutation.EXON_NAME, "Exon " + criteria.getExonNumber()).or().equals(Mutation.EXON_NAME, "IVS" + criteria.getExonNumber());
        if (criteria.getMid() != null)
            query = query.equals(Mutation.IDENTIFIER, criteria.getMid());
        if (StringUtils.length(criteria.getInheritance()) > 2)
            query = query.like(Mutation.INHERITANCE, criteria.getInheritance() + "%");
        if (criteria.getMutationId() != null)
            query = query.equals(Mutation.ID, criteria.getMutationId());
        if (StringUtils.length(criteria.getPhenotypeName()) > 2) {
            // TODO: add proper join capability
            List<ObservedValue> phenotypes = this.db.query(ObservedValue.class).equals(ObservedValue.VALUE, criteria.getPhenotypeName()).find();
            for (ObservedValue phenotype : phenotypes) {
                Patient patient = this.db.findById(Patient.class, phenotype.getTarget_Id());
                List<Integer> mutationIds = patient.getMutations_Id();
                if (mutationIds.size() > 0)
                    query = query.in(Mutation.ID, mutationIds);
            }
        }
        // }
        if (criteria.getPid() != null) {
            // TODO: add proper join capability
            List<Patient> patients = this.db.query(Patient.class).equals(Patient.IDENTIFIER, criteria.getPid()).find();
            List<Integer> mutationIds = new ArrayList<Integer>();
            for (Patient patient : patients) {
                mutationIds.addAll(patient.getMutations_Id());
            }
            if (mutationIds.size() > 0)
                query = query.in(Mutation.ID, mutationIds);
        }
        if (criteria.getProteinDomainId() != null) {
            // TODO: add proper join capability
            // List<Exon_ProteinDomain> epds =
            // this.db.query(Exon_ProteinDomain.class).equals(Exon_ProteinDomain.PROTEINDOMAIN,
            // criteria.getProteinDomainId()).find();
            // //List<Tuple> epds =
            // this.db.sql(String.format("SELECT Exon FROM Exon_proteinDomain WHERE proteinDomain = %d",
            // criteria.getProteinDomainId()));
            // List<Integer> exonIds = new ArrayList<Integer>();
            // for (Exon_ProteinDomain epd : epds)
            // exonIds.add(epd.getExon_Id());
            // if (exonIds.size() > 0)
            // query = query.in(Mutation.EXON, exonIds);
            List<Exon> exons = this.db.query(Exon.class).equals(Exon.PROTEINDOMAIN, criteria.getProteinDomainId()).find();
            List<Integer> exonIds = new ArrayList<Integer>();
            for (Exon exon : exons) exonIds.add(exon.getId());
            if (exonIds.size() > 0)
                query = query.in(Mutation.EXON, exonIds);
        }
        if (StringUtils.length(criteria.getPublication()) > 2) {
            List<Publication> publications = this.db.query(Publication.class).like(Publication.NAME, criteria.getPublication() + "%").or().like(Publication.TITLE, "%" + criteria.getPublication() + "%").find();
            List<Integer> publicationIds = new ArrayList<Integer>();
            for (Publication publication : publications) publicationIds.add(publication.getId());
            if (publicationIds.size() > 0) {
                List<Patient> patients = this.db.query(Patient.class).in(Patient.PATIENTREFERENCES, publicationIds).find();
                List<Integer> mutationIds = new ArrayList<Integer>();
                for (Patient patient : patients) {
                    mutationIds.addAll(patient.getMutations_Id());
                }
                if (mutationIds.size() > 0)
                    query = query.in(Mutation.ID, mutationIds);
            }
        }
        if (criteria.getReportedAsSNP() != null)
            query = query.equals(Mutation.REPORTEDSNP, criteria.getReportedAsSNP());
        if (StringUtils.length(criteria.getType()) > 2)
            query = query.like(Mutation.TYPE_, criteria.getType() + "%");
        if (StringUtils.length(criteria.getVariation()) > 0)
            query = query.equals(Mutation.CDNA_NOTATION, criteria.getVariation()).or().equals(Mutation.CDNA_NOTATION, "c." + criteria.getVariation()).or().equals(Mutation.AA_NOTATION, criteria.getVariation()).or().equals(Mutation.AA_NOTATION, "p." + criteria.getVariation());
        if (query.getRules().length > 0)
            return query.sortASC(Mutation.IDENTIFIER).find();
        else
            return new ArrayList<Mutation>();
    } else if (this.db instanceof JpaDatabase) {
        CriteriaBuilder cb = this.db.getEntityManager().getCriteriaBuilder();
        CriteriaQuery<Mutation> query = cb.createQuery(Mutation.class);
        // Metamodel metaModel = this.db.getEntityManager().getMetamodel();
        // EntityType<Mutation> Mutation_ =
        // metaModel.entity(Mutation.class);
        Root<Mutation> mutation = query.from(Mutation.class);
        query.select(mutation);
        List<Predicate> mutationCriteria = new ArrayList<Predicate>();
        if (criteria.getCdnaPosition() != null)
            mutationCriteria.add(cb.equal(mutation.get("cdna_position"), criteria.getCdnaPosition()));
        if (criteria.getCodonChangeNumber() != null)
            mutationCriteria.add(cb.equal(mutation.get("aa_position"), criteria.getCodonChangeNumber()));
        if (StringUtils.length(criteria.getConsequence()) > 2)
            mutationCriteria.add(cb.like(mutation.<String>get("consequence"), criteria.getConsequence() + "%"));
        if (criteria.getExonId() != null || criteria.getExonName() != null || criteria.getExonNumber() != null || criteria.getProteinDomainId() != null) {
            Join<Mutation, Exon> exon = mutation.join("exon", JoinType.LEFT);
            if (criteria.getExonId() != null)
                mutationCriteria.add(cb.equal(exon.get("id"), criteria.getExonId()));
            if (criteria.getExonName() != null)
                mutationCriteria.add(cb.or(cb.like(exon.<String>get("name"), "Exon " + criteria.getExonName()), cb.like(exon.<String>get("name"), "IVS" + criteria.getExonName())));
            if (criteria.getExonNumber() != null)
                mutationCriteria.add(cb.or(cb.like(exon.<String>get("name"), "Exon " + criteria.getExonNumber()), cb.like(exon.<String>get("name"), "IVS" + criteria.getExonNumber())));
            if (criteria.getProteinDomainId() != null) {
                Join<Exon, ProteinDomain> proteinDomain = exon.join("proteinDomain", JoinType.LEFT);
                mutationCriteria.add(cb.equal(proteinDomain.get("id"), criteria.getProteinDomainId()));
            }
        }
        if (criteria.getMid() != null)
            mutationCriteria.add(cb.equal(mutation.get("identifier"), criteria.getMid()));
        if (StringUtils.length(criteria.getInheritance()) > 2)
            mutationCriteria.add(cb.like(mutation.<String>get("inheritance"), criteria.getInheritance() + "%"));
        if (criteria.getMutationId() != null)
            mutationCriteria.add(cb.equal(mutation.get("id"), criteria.getMutationId()));
        if (criteria.getPid() != null || criteria.getPhenotypeId() != null || StringUtils.length(criteria.getPhenotypeName()) > 2 || StringUtils.length(criteria.getPublication()) > 2) {
            Join<Mutation, Patient> patient = mutation.join("mutationsCollection", JoinType.LEFT);
            if (criteria.getPid() != null)
                mutationCriteria.add(cb.equal(patient.get("identifier"), criteria.getPid()));
            if (criteria.getPhenotypeId() != null) {
            }
            if (StringUtils.length(criteria.getPhenotypeName()) > 2) {
                Join<Patient, ObservedValue> observedValues = patient.join("targetObservedValueCollection", JoinType.LEFT);
                Join<ObservedValue, ObservableFeature> observableFeatures = observedValues.join("feature", JoinType.LEFT);
                mutationCriteria.add(cb.or(cb.and(cb.equal(observableFeatures.get("name"), "Phenotype"), cb.equal(observedValues.get("value"), criteria.getPhenotypeName())), cb.and(cb.equal(observableFeatures.get("name"), criteria.getPhenotypeName()), cb.equal(observedValues.get("value"), "yes"))));
            }
            if (StringUtils.length(criteria.getPublication()) > 2) {
                Join<Patient, Publication> publication = patient.join("patientreferences", JoinType.LEFT);
                mutationCriteria.add(cb.or(cb.like(publication.<String>get("name"), "%" + criteria.getPublication() + "%"), cb.like(publication.<String>get("title"), "%" + criteria.getPublication() + "%")));
            }
        }
        if (criteria.getReportedAsSNP() != null)
            mutationCriteria.add(cb.equal(mutation.get("reportedsnp"), criteria.getMutationId()));
        if (StringUtils.length(criteria.getType()) > 2)
            mutationCriteria.add(cb.like(mutation.<String>get("type_"), criteria.getType() + "%"));
        if (StringUtils.length(criteria.getVariation()) > 0)
            mutationCriteria.add(cb.or(cb.equal(mutation.get("cdna_notation"), criteria.getVariation()), cb.equal(mutation.<String>get("cdna_notation"), "c." + criteria.getVariation()), cb.equal(mutation.get("aa_notation"), criteria.getVariation()), cb.equal(mutation.get("cdna_notation"), "p." + criteria.getVariation())));
        if (mutationCriteria.size() > 0) {
            query.where(cb.and(mutationCriteria.toArray(new Predicate[0])));
            query.orderBy(cb.asc(mutation.get("identifier")));
            return this.db.getEntityManager().createQuery(query).getResultList();
        } else
            return new ArrayList<Mutation>();
    } else
        throw new DatabaseException("Unsupported database mapper");
}
Example 38
Project: spring-data-jpa-master  File: QueryUtils.java View source code
@SuppressWarnings("unchecked")
static <T> Expression<T> toExpressionRecursively(From<?, ?> from, PropertyPath property) {
    Bindable<?> propertyPathModel = null;
    Bindable<?> model = from.getModel();
    String segment = property.getSegment();
    if (model instanceof ManagedType) {
        /*
			 *  Required to keep support for EclipseLink 2.4.x. TODO: Remove once we drop that (probably Dijkstra M1)
			 *  See: https://bugs.eclipse.org/bugs/show_bug.cgi?id=413892
			 */
        propertyPathModel = (Bindable<?>) ((ManagedType<?>) model).getAttribute(segment);
    } else {
        propertyPathModel = from.get(segment).getModel();
    }
    if (requiresJoin(propertyPathModel, model instanceof PluralAttribute) && !isAlreadyFetched(from, segment)) {
        Join<?, ?> join = getOrCreateJoin(from, segment);
        return (Expression<T>) (property.hasNext() ? toExpressionRecursively(join, property.next()) : join);
    } else {
        Path<Object> path = from.get(segment);
        return (Expression<T>) (property.hasNext() ? toExpressionRecursively(path, property.next()) : path);
    }
}
Example 39
Project: artificer-master  File: ArtificerToHibernateQueryVisitor.java View source code
/**
     * @see org.artificer.common.query.xpath.visitors.XPathVisitor#visit(org.artificer.common.query.xpath.ast.ForwardPropertyStep)
     */
@Override
public void visit(ForwardPropertyStep node) {
    if (node.getPropertyQName() != null) {
        QName property = node.getPropertyQName();
        if (property.getNamespaceURI() == null || "".equals(property.getNamespaceURI()))
            property = new QName(ArtificerConstants.SRAMP_NS, property.getLocalPart());
        if (property.getNamespaceURI().equals(ArtificerConstants.SRAMP_NS)) {
            if (corePropertyMap.containsKey(property)) {
                propertyContext = corePropertyMap.get(property);
                customPropertySubquery = null;
            } else {
                // Note: Typically, you'd expect to see a really simple MapJoin w/ key and value predicates.
                // However, *negation* ("not()") is needed and is tricky when just using a join.  Instead, use
                // an "a1.id in (select a2.id from ArtificerArtifact a2 [map join and predicates)" -- easily negated.
                customPropertySubquery = query.subquery(ArtificerArtifact.class);
                From customPropertyFrom = customPropertySubquery.from(ArtificerArtifact.class);
                Join customPropertyJoin = customPropertyFrom.join("properties");
                customPropertySubquery.select(customPropertyFrom.get("id"));
                customPropertyPredicates = new ArrayList<>();
                customPropertyPredicates.add(criteriaBuilder.equal(customPropertyFrom.get("id"), from.get("id")));
                customPropertyPredicates.add(criteriaBuilder.equal(customPropertyJoin.get("key"), property.getLocalPart()));
                customPropertyValuePath = customPropertyJoin.get("value");
                predicates.add(criteriaBuilder.exists(customPropertySubquery));
                propertyContext = null;
            }
        } else {
            throw new RuntimeException(Messages.i18n.format("XP_INVALID_PROPERTY_NS", property.getNamespaceURI()));
        }
    }
}
Example 40
Project: Broadleaf-eCommerce-master  File: ProductDaoImpl.java View source code
protected List<Product> readFilteredActiveProductsByQueryInternal(String query, Date currentDate, SearchCriteria searchCriteria) {
    // Set up the criteria query that specifies we want to return Products
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Product> criteria = builder.createQuery(Product.class);
    // The root of our search is Product since we are searching
    Root<ProductImpl> product = criteria.from(ProductImpl.class);
    // We also want to filter on attributes from sku and productAttributes
    Join<Product, Sku> sku = product.join("defaultSku");
    // Product objects are what we want back
    criteria.select(product);
    // We only want results that match the search query
    List<Predicate> restrictions = new ArrayList<Predicate>();
    String lq = query.toLowerCase();
    restrictions.add(builder.or(builder.like(builder.lower(sku.get("name").as(String.class)), '%' + lq + '%'), builder.like(builder.lower(sku.get("longDescription").as(String.class)), '%' + lq + '%')));
    attachSearchCriteria(searchCriteria, product, sku, restrictions);
    attachActiveRestriction(currentDate, product, sku, restrictions);
    attachOrderBy(searchCriteria, product, sku, criteria);
    // Execute the query with the restrictions
    criteria.where(restrictions.toArray(new Predicate[restrictions.size()]));
    TypedQuery<Product> typedQuery = em.createQuery(criteria);
    return typedQuery.getResultList();
}
Example 41
Project: BroadleafCommerce-master  File: ProductDaoImpl.java View source code
protected List<Product> readFilteredActiveProductsByQueryInternal(String query, Date currentDate, SearchCriteria searchCriteria) {
    // Set up the criteria query that specifies we want to return Products
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Product> criteria = builder.createQuery(Product.class);
    // The root of our search is Product since we are searching
    Root<ProductImpl> product = criteria.from(ProductImpl.class);
    // We also want to filter on attributes from sku and productAttributes
    Join<Product, Sku> sku = product.join("defaultSku");
    // Product objects are what we want back
    criteria.select(product);
    // We only want results that match the search query
    List<Predicate> restrictions = new ArrayList<Predicate>();
    String lq = query.toLowerCase();
    restrictions.add(builder.or(builder.like(builder.lower(sku.get("name").as(String.class)), '%' + lq + '%'), builder.like(builder.lower(sku.get("longDescription").as(String.class)), '%' + lq + '%')));
    attachSearchCriteria(searchCriteria, product, sku, restrictions);
    attachActiveRestriction(currentDate, product, sku, restrictions);
    attachOrderBy(searchCriteria, product, sku, criteria);
    // Execute the query with the restrictions
    criteria.where(restrictions.toArray(new Predicate[restrictions.size()]));
    TypedQuery<Product> typedQuery = em.createQuery(criteria);
    return typedQuery.getResultList();
}
Example 42
Project: commerce-master  File: ProductDaoImpl.java View source code
protected List<Product> readFilteredActiveProductsByQueryInternal(String query, Date currentDate, SearchCriteria searchCriteria) {
    // Set up the criteria query that specifies we want to return Products
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Product> criteria = builder.createQuery(Product.class);
    // The root of our search is Product since we are searching
    Root<ProductImpl> product = criteria.from(ProductImpl.class);
    // We also want to filter on attributes from sku and productAttributes
    Join<Product, Sku> sku = product.join("defaultSku");
    // Product objects are what we want back
    criteria.select(product);
    // We only want results that match the search query
    List<Predicate> restrictions = new ArrayList<Predicate>();
    String lq = query.toLowerCase();
    restrictions.add(builder.or(builder.like(builder.lower(sku.get("name").as(String.class)), '%' + lq + '%'), builder.like(builder.lower(sku.get("longDescription").as(String.class)), '%' + lq + '%')));
    attachSearchCriteria(searchCriteria, product, sku, restrictions);
    attachActiveRestriction(currentDate, product, sku, restrictions);
    attachOrderBy(searchCriteria, product, sku, criteria);
    // Execute the query with the restrictions
    criteria.where(restrictions.toArray(new Predicate[restrictions.size()]));
    TypedQuery<Product> typedQuery = em.createQuery(criteria);
    return typedQuery.getResultList();
}
Example 43
Project: hibernate-semantic-query-master  File: CriteriaInterpreter.java View source code
private void bindJoins(JpaFrom<?, ?> lhs, SqmNavigableReference lhsBinding, SqmFromElementSpace space) {
    if (!SqmNavigableSourceReference.class.isInstance(lhsBinding)) {
        if (!lhs.getJoins().isEmpty()) {
            throw new ParsingException("Attempt to bind joins against a NavigableBinding that is not also a NavigableSourceBinding ");
        } else {
            return;
        }
    }
    for (Join<?, ?> join : lhs.getJoins()) {
        makeSqmAttributeJoin((SqmNavigableSourceReference) lhsBinding, space, join);
    }
}
Example 44
Project: rsql-jpa-master  File: PredicateBuilder.java View source code
/**
     * Find a property path in the graph from startRoot
     *
     * @param propertyPath   The property path to find.
     * @param startRoot      From that property path depends on.
     * @param entityManager  JPA EntityManager.
     * @param misc           Facade with all necessary tools for predicate creation.
     * @return               The Path for the property path
     * @throws               IllegalArgumentException if attribute of the given property name does not exist
     */
public static <T> Path<?> findPropertyPath(String propertyPath, Path startRoot, EntityManager entityManager, BuilderTools misc) {
    String[] graph = propertyPath.split("\\.");
    Metamodel metaModel = entityManager.getMetamodel();
    ManagedType<?> classMetadata = metaModel.managedType(startRoot.getJavaType());
    Path<?> root = startRoot;
    for (String property : graph) {
        String mappedProperty = misc.getPropertiesMapper().translate(property, classMetadata.getJavaType());
        if (!mappedProperty.equals(property)) {
            root = findPropertyPath(mappedProperty, root, entityManager, misc);
        } else {
            if (!hasPropertyName(mappedProperty, classMetadata)) {
                throw new IllegalArgumentException("Unknown property: " + mappedProperty + " from entity " + classMetadata.getJavaType().getName());
            }
            if (isAssociationType(mappedProperty, classMetadata)) {
                Class<?> associationType = findPropertyType(mappedProperty, classMetadata);
                String previousClass = classMetadata.getJavaType().getName();
                classMetadata = metaModel.managedType(associationType);
                LOG.log(Level.INFO, "Create a join between {0} and {1}.", new Object[] { previousClass, classMetadata.getJavaType().getName() });
                if (root instanceof Join) {
                    root = root.get(mappedProperty);
                } else {
                    root = ((From) root).join(mappedProperty);
                }
            } else {
                LOG.log(Level.INFO, "Create property path for type {0} property {1}.", new Object[] { classMetadata.getJavaType().getName(), mappedProperty });
                root = root.get(mappedProperty);
                if (isEmbeddedType(mappedProperty, classMetadata)) {
                    Class<?> embeddedType = findPropertyType(mappedProperty, classMetadata);
                    classMetadata = metaModel.managedType(embeddedType);
                }
            }
        }
    }
    return root;
}
Example 45
Project: lunifera-dsl-master  File: EntityDelegate.java View source code
/**
	 * Translates SortBy instances, which possibly contain nested properties
	 * (e.g. name.firstName, name.lastName) into Order instances which can be
	 * used in a CriteriaQuery.
	 * 
	 * @param sortBy
	 *            the SortBy instance to translate
	 * @param swapSortOrder
	 *            swaps the specified sort order if true.
	 * @param cb
	 *            the {@link CriteriaBuilder} to use
	 * @param root
	 *            the {@link CriteriaQuery} {@link Root} to be used.
	 * @return
	 */
protected Order translateSortBy(SortBy sortBy, boolean swapSortOrder, CriteriaBuilder cb, Root<T> root) {
    String sortedPropId = sortBy.getPropertyId().toString();
    // First split the id and build a Path.
    String[] idStrings = sortedPropId.split("\\.");
    Path<T> path = null;
    if (idStrings.length > 1 && !isEmbedded(idStrings[0])) {
        // This is a nested property, we need to LEFT JOIN
        path = root.join(idStrings[0], JoinType.LEFT);
        for (int i = 1; i < idStrings.length; i++) {
            if (i < idStrings.length - 1) {
                path = ((Join<?, ?>) path).join(idStrings[i], JoinType.LEFT);
            } else {
                path = path.get(idStrings[i]);
            }
        }
    } else {
        // non-nested or embedded, we can select as usual
        path = LAdvancedFilterableSupport.getPropertyPathTyped(root, sortedPropId);
    }
    // Make and return the Order instances.
    if (sortBy.isAscending() != swapSortOrder) {
        return cb.asc(path);
    } else {
        return cb.desc(path);
    }
}
Example 46
Project: hapi-fhir-master  File: SearchBuilder.java View source code
private void addPredicateDate(String theResourceName, String theParamName, List<? extends IQueryParameterType> theList) {
    Join<ResourceTable, ResourceIndexedSearchParamDate> join = myResourceTableRoot.join("myParamsDate", JoinType.LEFT);
    if (theList.get(0).getMissing() != null) {
        addPredicateParamMissing(theResourceName, theParamName, theList.get(0).getMissing(), join);
        return;
    }
    List<Predicate> codePredicates = new ArrayList<Predicate>();
    for (IQueryParameterType nextOr : theList) {
        IQueryParameterType params = nextOr;
        Predicate p = createPredicateDate(params, theResourceName, theParamName, myBuilder, join);
        codePredicates.add(p);
    }
    Predicate orPredicates = myBuilder.or(toArray(codePredicates));
    myPredicates.add(orPredicates);
}
Example 47
Project: picketlink-master  File: JPAIdentityStore.java View source code
@Override
public <V extends IdentityType> List<V> fetchQueryResults(IdentityContext context, IdentityQuery<V> identityQuery) {
    List<V> result = new ArrayList<V>();
    Class<V> type = identityQuery.getIdentityType();
    for (Condition condition : identityQuery.getConditions()) {
        if (IdentityType.ID.equals(condition.getParameter())) {
            if (!EqualCondition.class.isInstance(condition)) {
                throw new IdentityManagementException("Only equality conditions are allowed when queryng based on the identifier.");
            }
            EqualCondition equalCondition = (EqualCondition) condition;
            Object value = equalCondition.getValue();
            if (value != null) {
                V identityType = (V) lookupIdentityTypeById(context, type, value.toString());
                if (identityType != null) {
                    result.add(identityType);
                }
            }
            return result;
        }
    }
    EntityMapper rootMapper = getRootMapper(type);
    EntityManager entityManager = getEntityManager(context);
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery cq = cb.createQuery(rootMapper.getEntityType());
    List<Predicate> predicates = new ArrayList<Predicate>();
    Root<?> rootEntity = cq.from(rootMapper.getEntityType());
    Partition partition = context.getPartition();
    for (Condition condition : identityQuery.getConditions()) {
        if (IdentityType.PARTITION.equals(condition.getParameter())) {
            if (!EqualCondition.class.isInstance(condition)) {
                throw new IdentityManagementException("Only equality conditions are allowed when queryng based on a partition.");
            }
            EqualCondition equalCondition = (EqualCondition) condition;
            Object value = equalCondition.getValue();
            if (value != null) {
                partition = (Partition) value;
            }
        }
    }
    Entry<Property, Property> partitionProperty = rootMapper.getProperty(OwnerReference.class);
    if (partitionProperty != null && getConfig().supportsPartition()) {
        Join<Object, Object> join = rootEntity.join(partitionProperty.getValue().getName());
        predicates.add(cb.equal(join, entityManager.find(partitionProperty.getValue().getJavaClass(), partition.getId())));
    }
    if (!IdentityType.class.equals(type)) {
        Property typeProperty = rootMapper.getProperty(type, IdentityClass.class).getValue();
        predicates.add(cb.equal(rootEntity.get(typeProperty.getName()), type.getName()));
    }
    for (Condition condition : identityQuery.getConditions()) {
        QueryParameter queryParameter = condition.getParameter();
        if (IdentityType.PARTITION.equals(queryParameter)) {
            continue;
        }
        if (AttributeParameter.class.isInstance(queryParameter)) {
            AttributeParameter attributeParameter = (AttributeParameter) queryParameter;
            EntityMapper parameterEntityMapper = getEntityMapperForProperty(type, attributeParameter.getName());
            if (parameterEntityMapper != null) {
                Property attributeProperty = (Property) parameterEntityMapper.getProperty(type, attributeParameter.getName()).getValue();
                Root<?> attributeOwnerEntity = rootEntity;
                if (!parameterEntityMapper.getEntityType().equals(rootMapper.getEntityType())) {
                    attributeOwnerEntity = cq.from(parameterEntityMapper.getEntityType());
                    Property ownerProperty = parameterEntityMapper.getProperty(OwnerReference.class).getValue();
                    if (ownerProperty != null) {
                        if (ownerProperty.getAnnotatedElement().isAnnotationPresent(Identifier.class)) {
                            predicates.add(cb.and(cb.equal(attributeOwnerEntity, rootEntity)));
                        } else {
                            predicates.add(cb.and(cb.equal(attributeOwnerEntity.get(ownerProperty.getName()), rootEntity)));
                        }
                    }
                }
                addCondition(entityManager, cb, predicates, condition, attributeProperty, attributeOwnerEntity, false);
            } else if (getConfig().supportsAttribute()) {
                addAttributeQueryPredicates(type, entityManager, cb, cq, rootEntity, predicates, attributeParameter, condition, null);
            }
        }
    }
    Property idProperty = rootMapper.getProperty(Identifier.class).getValue();
    cq.select(rootEntity.get(idProperty.getName()));
    cq.where(predicates.toArray(new Predicate[predicates.size()]));
    if (!identityQuery.getSorting().isEmpty()) {
        List<Order> orders = new ArrayList<Order>();
        for (Sort sort : identityQuery.getSorting()) {
            QueryParameter queryParameter = sort.getParameter();
            if (!AttributeParameter.class.isInstance(queryParameter)) {
                throw new IdentityManagementException("Sorting parameter is not a [" + AttributeParameter.class + "].");
            }
            AttributeParameter attributeParameter = (AttributeParameter) queryParameter;
            if (sort.isAscending()) {
                orders.add(cb.asc(rootEntity.get(attributeParameter.getName())));
            } else {
                orders.add(cb.desc(rootEntity.get(attributeParameter.getName())));
            }
        }
        cq.orderBy(orders);
    }
    Query query = entityManager.createQuery(cq);
    if (identityQuery.getLimit() > 0) {
        query.setMaxResults(identityQuery.getLimit());
        if (identityQuery.getOffset() > 0) {
            query.setFirstResult(identityQuery.getOffset());
        }
    }
    for (Object entity : query.getResultList()) {
        result.add(rootMapper.<V>createType(entityManager.find(rootMapper.getEntityType(), entity), entityManager));
    }
    return result;
}
Example 48
Project: uaicriteria-master  File: JoinWrapper.java View source code
public JoinWrapper createJoinFromJoin(final String joinName, final JoinType joinType) {
    if (join != null) {
        final Join innerJoin = join.join(joinName, joinType);
        return new JoinWrapper(innerJoin);
    }
    final Fetch innerJoin = joinFetch.fetch(joinName, joinType);
    return new JoinWrapper(innerJoin);
}
Example 49
Project: hexa.tools-master  File: RootImpl.java View source code
@Override
public Set<Join<T, ?>> getJoins() {
    // TODO Auto-generated method stub
    return null;
}
Example 50
Project: jena-sparql-api-master  File: FromImpl.java View source code
@Override
public Set<Join<X, ?>> getJoins() {
    throw new UnsupportedOperationException();
}
Example 51
Project: raidenjpa-master  File: RaidenRoot.java View source code
@Override
public Set<Join<X, ?>> getJoins() {
    // TODO Auto-generated method stub
    return null;
}
Example 52
Project: sculptor-master  File: JpaCriteriaQueryAccessBase.java View source code
private Join<?, ?> getExplicitJoinForPath(Path<?> path, String property) {
    Path<?> parentPath = path.getParentPath();
    if (From.class.isAssignableFrom(parentPath.getClass())) {
        return ((From<?, ?>) parentPath).join(property);
    }
    throw new QueryConfigException("Can't create a explicit join for property " + property);
}
Example 53
Project: xtext-master  File: JpaCriteriaQueryAccessBase.java View source code
private Join<?, ?> getExplicitJoinForPath(Path<?> path, String property) {
    Path<?> parentPath = path.getParentPath();
    if (From.class.isAssignableFrom(parentPath.getClass())) {
        return ((From<?, ?>) parentPath).join(property);
    }
    throw new QueryConfigException("Can't create a explicit join for property " + property);
}
Example 54
Project: eucalyptus-master  File: Entities.java View source code
/**
     * Join on the given attribute and restriction.
     *
     * @param attribute The entity attribute that defines the relation
     * @param restriction Restriction on the joined entity
     * @param <J> The joined entity type
     * @return This criteria query for method chaining.
     */
public <J> B join(@Nonnull final SingularAttribute<? super E, J> attribute, @Nonnull final EntityRestriction<J> restriction) {
    final Join<E, J> join = context.from.join(attribute);
    context.restrictions.add(restriction.build(context.builder, join));
    return self();
}