Example usage for javax.persistence.criteria Join get

List of usage examples for javax.persistence.criteria Join get

Introduction

In this page you can find the example usage for javax.persistence.criteria Join get.

Prototype

<Y> Path<Y> get(SingularAttribute<? super X, Y> attribute);

Source Link

Document

Create a path corresponding to the referenced single-valued attribute.

Usage

From source file:org.openregistry.core.repository.jpa.JpaPersonRepository.java

@Override
public List<Person> findByUnknownIdentifier(final String identifierValue) throws RepositoryAccessException {
    final CriteriaBuilder criteriaBuilder = this.entityManager.getCriteriaBuilder();

    final CriteriaQuery<JpaPersonImpl> c = criteriaBuilder.createQuery(JpaPersonImpl.class);
    final Root<JpaPersonImpl> person = c.from(JpaPersonImpl.class);
    final Join<JpaPersonImpl, JpaIdentifierImpl> identifier = person.join(JpaPersonImpl_.identifiers);

    c.select(person).distinct(true)//from w  w  w . j  ava  2s.co m
            .where(criteriaBuilder.like(identifier.get(JpaIdentifierImpl_.value), identifierValue + "%"));

    final List<JpaPersonImpl> persons = this.entityManager.createQuery(c).getResultList();

    return new ArrayList<Person>(persons);
}

From source file:hr.diskobolos.persistence.impl.EvaluationAnswerPersistenceImpl.java

@Override
public Long fetchNumberOfMemberRegistersWithoutTerms() {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Long> cq = cb.createQuery(Long.class);
    Root<MemberRegister> memberRegister = cq.from(MemberRegister.class);
    Subquery<Long> sq = cq.subquery(Long.class);
    Root<EvaluationAnswer> evaluationAnswer = sq.from(EvaluationAnswer.class);
    Join<EvaluationAnswer, QuestionChoicesDef> choiceDef = evaluationAnswer.join(EvaluationAnswer_.answer);
    Join<QuestionChoicesDef, EvaluationQuestionDef> questionDef = choiceDef
            .join(QuestionChoicesDef_.evaluationQuestionDef);
    ParameterExpression<QuestionnaireType> questionnaireType = cb.parameter(QuestionnaireType.class,
            "questionnaireType");
    sq.select(evaluationAnswer.get("memberRegister").get("id"))
            .where(cb.equal(questionDef.get(EvaluationQuestionDef_.questionnaireType), questionnaireType));
    cq.select(cb.count(memberRegister.get("id"))).where(cb.not(cb.in(memberRegister.get("id")).value(sq)));
    TypedQuery<Long> query = entityManager.createQuery(cq);
    query.setParameter("questionnaireType", QuestionnaireType.TERMS_OF_CONDITION);
    return query.getSingleResult();
}

From source file:com.vladmihalcea.HibernateCriteriaTest.java

private List<Product> getProducts_Mercifully() {
    return transactionTemplate.execute(new TransactionCallback<List<Product>>() {
        @Override//from   ww w .ja  v a 2  s .  co  m
        public List<Product> doInTransaction(TransactionStatus transactionStatus) {
            CriteriaBuilder cb = entityManager.getCriteriaBuilder();
            CriteriaQuery<Product> query = cb.createQuery(Product.class);
            Root<Image> imageRoot = query.from(Image.class);
            Join<Image, Product> productJoin = imageRoot.join(Image_.product);
            query.select(productJoin);
            query.distinct(true);
            List<Predicate> criteria = new ArrayList<Predicate>();
            criteria.add(cb.like(cb.lower(productJoin.get(Product_.name)), "%tv%"));
            criteria.add(cb.gt(imageRoot.get(Image_.index), 0));
            query.where(cb.and(criteria.toArray(new Predicate[criteria.size()])));
            return entityManager.createQuery(query).getResultList();
        }
    });
}

From source file:se.kth.csc.persist.JPAStore.java

@Override
public QueuePosition fetchQueuePositionWithQueueAndUser(String queueName, String userName) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<QueuePosition> q = cb.createQuery(QueuePosition.class);

    Root<QueuePosition> queuePosition = q.from(QueuePosition.class);
    Join<QueuePosition, Queue> queue = queuePosition.join(QueuePosition_.queue);
    Join<QueuePosition, Account> account = queuePosition.join(QueuePosition_.account);

    try {/*from ww  w  .  j  av  a 2 s. c  om*/
        return entityManager
                .createQuery(
                        q.select(queuePosition)
                                .where(cb.and(cb.equal(queue.get(Queue_.name), queueName),
                                        cb.equal(account.get(Account_.principalName), userName))))
                .getSingleResult();
    } catch (NoResultException e) {
        return null;
    }
}

From source file:com.vladmihalcea.HibernateCriteriaTest.java

private Product getProduct_Mercifully() {
    return transactionTemplate.execute(new TransactionCallback<Product>() {
        @Override//from   ww w. j a  va  2s  .c o m
        public Product doInTransaction(TransactionStatus transactionStatus) {
            CriteriaBuilder cb = entityManager.getCriteriaBuilder();
            CriteriaQuery<Product> query = cb.createQuery(Product.class);
            Root<Product> productRoot = query.from(Product.class);
            Join<Product, WarehouseProductInfo> warehouseProductInfoJoin = productRoot
                    .join(Product_.warehouseProductInfo);

            query.select(productRoot).where(cb.and(cb.equal(productRoot.get(Product_.code), "tvCode"),
                    cb.gt(warehouseProductInfoJoin.get(WarehouseProductInfo_.quantity), 50)));
            return entityManager.createQuery(query).getSingleResult();
        }
    });
}

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

/**
 * Looks up an area by name/*from  www . j a va  2 s . c  om*/
 * @param name the name to search for
 * @param lang the language. Optional
 * @param parentId the parent ID. Optional
 * @return The matching area, or null if not found
 */
public Area findByName(String name, String lang, Integer parentId) {
    // Sanity check
    if (StringUtils.isBlank(name)) {
        return null;
    }

    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Area> areaQuery = builder.createQuery(Area.class);

    Root<Area> areaRoot = areaQuery.from(Area.class);

    // Build the predicate
    PredicateHelper<Area> predicateBuilder = new PredicateHelper<>(builder, areaQuery);

    // Match the name
    Join<Area, AreaDesc> descs = areaRoot.join("descs", JoinType.LEFT);
    predicateBuilder.like(descs.get("name"), name);
    // Optionally, match the language
    if (StringUtils.isNotBlank(lang)) {
        predicateBuilder.equals(descs.get("lang"), lang);
    }

    // Optionally, match the parent
    if (parentId != null) {
        areaRoot.join("parent", JoinType.LEFT);
        Path<Area> parent = areaRoot.get("parent");
        predicateBuilder.equals(parent.get("id"), parentId);
    }

    // Complete the query
    areaQuery.select(areaRoot).distinct(true).where(predicateBuilder.where());

    // Execute the query and update the search result
    List<Area> result = em.createQuery(areaQuery).getResultList();

    return result.size() > 0 ? result.get(0) : null;
}

From source file:ch.puzzle.itc.mobiliar.business.resourcerelation.control.ResourceRelationService.java

public List<ConsumedResourceRelationEntity> getConsumedSlaveRelations(ResourceEntity slaveResource) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<ConsumedResourceRelationEntity> q = cb.createQuery(ConsumedResourceRelationEntity.class);
    Root<ConsumedResourceRelationEntity> r = q.from(ConsumedResourceRelationEntity.class);
    Join<ConsumedResourceRelationEntity, ResourceEntity> slaveResourceJoin = r.join("slaveResource");
    q.where(cb.equal(slaveResourceJoin.get("id"), slaveResource.getId()));

    TypedQuery<ConsumedResourceRelationEntity> query = entityManager.createQuery(q);
    return query.getResultList();
}

From source file:ch.puzzle.itc.mobiliar.business.resourcerelation.control.ResourceRelationService.java

public List<ProvidedResourceRelationEntity> getProvidedSlaveRelations(ResourceEntity slaveResource) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<ProvidedResourceRelationEntity> q = cb.createQuery(ProvidedResourceRelationEntity.class);
    Root<ProvidedResourceRelationEntity> r = q.from(ProvidedResourceRelationEntity.class);
    Join<ProvidedResourceRelationEntity, ResourceEntity> slaveResourceJoin = r.join("slaveResource");
    q.where(cb.equal(slaveResourceJoin.get("id"), slaveResource.getId()));

    TypedQuery<ProvidedResourceRelationEntity> query = entityManager.createQuery(q);
    return query.getResultList();
}

From source file:de.whs.poodle.repositories.StatisticsRepository.java

public List<Statistic> getStatistics(FeedbackSearchCriteria s, int instructorId, int limit) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Statistic> cq = cb.createQuery(Statistic.class);
    Root<Statistic> statistic = cq.from(Statistic.class);

    /* fetch the exercises immediately so they don't have to
     * be lazy-fetched one by one while rendering the table rows. */
    statistic.fetch("exercise");

    // join we need to match the course
    Join<Statistic, Course> course = statistic.join("courseTerm").join("course");

    // create empty "and" predicate
    Predicate where = cb.conjunction();

    // only non-empty
    Predicate notEmpty = cb.isFalse(statistic.get("empty"));
    where = cb.and(where, notEmpty);/*ww w. j a v  a  2 s.com*/

    // only statistics for courses that the instructor has access to
    Predicate hasInstructorAccessToCourse = cb.isTrue(cb.function("has_instructor_access_to_course",
            Boolean.class, course.get("id"), cb.literal(instructorId)));

    where = cb.and(where, hasInstructorAccessToCourse);

    // filter by courseId
    if (s.getCourseId() != 0) {
        Predicate courseMatches = cb.equal(course.get("id"), s.getCourseId());
        where = cb.and(where, courseMatches);
    }

    // filter by student
    if (s.getStudent() != null) {
        Predicate studentMatches = cb.equal(statistic.get("student").get("id"), s.getStudent().getId());
        where = cb.and(where, studentMatches);
    }

    cq.where(where);

    // order by date
    cq.orderBy(cb.desc(statistic.get("completedAt")));

    return em.createQuery(cq).setMaxResults(limit).getResultList();
}

From source file:org.wallride.service.PostService.java

/**
 *
 * @param language//from  ww  w . j ava  2 s  .c o  m
 * @param type
 * @return
 * @see PostService#updatePopularPosts(BlogLanguage, PopularPost.Type, int)
 */
@Cacheable(value = WallRideCacheConfiguration.POPULAR_POST_CACHE, key = "'list.type.' + #language + '.' + #type")
public SortedSet<PopularPost> getPopularPosts(String language, PopularPost.Type type) {
    Specification<PopularPost> spec = (root, query, cb) -> {
        Join<PopularPost, Post> post = (Join<PopularPost, Post>) root.fetch(PopularPost_.post);
        post.fetch(Post_.cover);
        post.fetch(Post_.author);

        List<Predicate> predicates = new ArrayList<>();
        predicates.add(cb.equal(root.get(PopularPost_.language), language));
        predicates.add(cb.equal(root.get(PopularPost_.type), type));
        predicates.add(cb.equal(post.get(Post_.status), Post.Status.PUBLISHED));
        return cb.and(predicates.toArray(new Predicate[0]));
    };
    return popularPostRepository.findAll(spec);
}