Example usage for javax.persistence.criteria CriteriaQuery from

List of usage examples for javax.persistence.criteria CriteriaQuery from

Introduction

In this page you can find the example usage for javax.persistence.criteria CriteriaQuery from.

Prototype

<X> Root<X> from(Class<X> entityClass);

Source Link

Document

Create and add a query root corresponding to the given entity, forming a cartesian product with any existing roots.

Usage

From source file:de.hopmann.repositories.cran.service.CRANPackageListingService.java

@PackageListingUpdate
public boolean isAvailable(String packageName, Version sourceVersion) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<CRANPackageEntity> query = cb.createQuery(CRANPackageEntity.class);
    Root<CRANPackageEntity> p = query.from(CRANPackageEntity.class);
    query.where(cb.and(/*from ww w .  ja v  a 2 s.c  om*/
            //
            cb.equal(p.get(PackageEntity_.name), packageName),
            cb.equal(p.get(PackageEntity_.version).get(Version_.versionNumber),
                    sourceVersion.getVersionNumber())));

    List<CRANPackageEntity> resultList = entityManager.createQuery(query).getResultList();
    return !resultList.isEmpty();
}

From source file:com.panguso.lc.analysis.format.dao.impl.DaoImpl.java

@Override
public long findCount() {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Long> criteriaQuery = cb.createQuery(Long.class);
    Root<T> customer = criteriaQuery.from(entityClass);
    criteriaQuery.select(cb.count(customer));
    Query query = em.createQuery(criteriaQuery);
    return (Long) query.getSingleResult();
}

From source file:com.panguso.lc.analysis.format.dao.impl.DaoImpl.java

@Override
public List<T> find(int pageNo, int pageSize) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<T> criteriaQuery = cb.createQuery(entityClass);
    Root<T> customer = criteriaQuery.from(entityClass);
    criteriaQuery.getRoots().add(customer);
    Query query = em.createQuery(criteriaQuery);
    query.setFirstResult(pageNo * pageSize);
    query.setMaxResults(pageSize);/*from   w  ww .  ja v a 2s.c  o m*/
    return query.getResultList();
}

From source file:org.jasig.portlet.blackboardvcportlet.dao.impl.PresentationDaoImpl.java

@Override
public void afterPropertiesSet() throws Exception {
    this.findAllPresentation = this
            .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<PresentationImpl>>() {
                @Override//from   www.  j  ava 2  s. co  m
                public CriteriaQuery<PresentationImpl> apply(CriteriaBuilder cb) {
                    final CriteriaQuery<PresentationImpl> criteriaQuery = cb
                            .createQuery(PresentationImpl.class);
                    final Root<PresentationImpl> definitionRoot = criteriaQuery.from(PresentationImpl.class);
                    criteriaQuery.select(definitionRoot);

                    return criteriaQuery;
                }
            });
}

From source file:ru.portal.services.TableServiceImpl.java

/**
 * TODO    ManyToMany//w  ww.  j  a va  2s.c om
 * @param entityClass
 * @param id
 * @return 
 */
@Override
public Map<EntityType<?>, Map<String, String>> findByEntityClassId(String entityClass, String id) {

    try {
        Class<?> cl = Class.forName(entityClass);
        EntityType<?> entityType = em.getEntityManagerFactory().getMetamodel().entity(cl);
        if (entityType != null && entityType.getBindableJavaType().getAnnotation(PortalTable.class) != null) {
            if (entityType.getBindableJavaType().getName().equals(entityClass)) {
                Class<?> bindableJavaType = entityType.getBindableJavaType();
                //select

                CriteriaBuilder cb = em.getCriteriaBuilder();
                CriteriaQuery<?> cq = cb.createQuery(bindableJavaType);
                Root<?> root = cq.from(User.class);

                cq.where(cb.equal(root.get("id"), Long.parseLong(id)));

                TypedQuery<?> query = em.createQuery(cq);
                ParameterExpression<Long> parameter = cb.parameter(Long.class, "id");
                //query.setParameter(parameter, Long.parseLong(id));
                //query.unwrap(org.hibernate.Query.class).getQueryString();

                Object result = query.getSingleResult();

                List<String> columns = getTableOrViewMetaData(entityClass);

                HashMap<String, String> res = new HashMap<>(columns.size());
                Class<? extends Object> clazz = result.getClass();
                for (String fieldName : columns) {
                    try {
                        Field field = clazz.getDeclaredField(fieldName);
                        field.setAccessible(true);
                        Object fieldValue = field.get(result);
                        res.put(fieldName, fieldValue.toString());
                    } catch (NoSuchFieldException | SecurityException | IllegalArgumentException
                            | IllegalAccessException ex) {
                        Logger.getLogger(TableServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

                System.out.println(res);
                Map<EntityType<?>, Map<String, String>> hm = new HashMap<>();
                hm.put(entityType, res);
                return hm;

            }
        }

    } catch (ClassNotFoundException ex) {
        Logger.getLogger(TableServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:ch.puzzle.itc.mobiliar.business.resourcegroup.control.ResourceGroupRepository.java

/**
 *
 * @param name/*from  w  w w . j  a  v  a 2s . co  m*/
 * @param resourceTypeId
 * @return
 */
public ResourceGroupEntity loadUniqueGroupByNameAndType(String name, Integer resourceTypeId) {
    ResourceGroupEntity result = null;
    try {
        CriteriaBuilder cb = entityManager.getCriteriaBuilder();
        CriteriaQuery<ResourceGroupEntity> q = cb.createQuery(ResourceGroupEntity.class);
        Root<ResourceGroupEntity> r = q.from(ResourceGroupEntity.class);
        r.fetch("resources");
        Join<ResourceGroupEntity, ResourceEntity> resources = r.join("resources");
        Predicate typePred = cb.equal(resources.get("resourceType").get("id"), resourceTypeId);
        Predicate resNamePred = cb.equal(resources.get("name"), name);

        q.where(cb.and(typePred, resNamePred));

        q.distinct(true);

        result = entityManager.createQuery(q).getSingleResult();
    } catch (NoResultException e) {
        // do nothing
    }
    return result;
}

From source file:eu.domibus.common.dao.MessageLogDao.java

public List<MessageLogEntry> findPaged(int from, int max, String column, boolean asc,
        HashMap<String, Object> filters) {

    CriteriaBuilder cb = this.em.getCriteriaBuilder();
    CriteriaQuery<MessageLogEntry> cq = cb.createQuery(MessageLogEntry.class);
    Root<MessageLogEntry> mle = cq.from(MessageLogEntry.class);
    cq.select(mle);/*w  w w.j  av  a 2 s .  c om*/
    List<Predicate> predicates = new ArrayList<Predicate>();
    for (Map.Entry<String, Object> filter : filters.entrySet()) {
        if (filter.getValue() != null) {
            if (filter.getValue() instanceof String) {
                if (!filter.getValue().toString().isEmpty()) {
                    switch (filter.getKey().toString()) {
                    case "receivedFrom":
                        predicates.add(cb.greaterThanOrEqualTo(mle.<Date>get("received"),
                                Timestamp.valueOf(filter.getValue().toString())));
                        break;
                    case "receivedTo":
                        predicates.add(cb.lessThanOrEqualTo(mle.<Date>get("received"),
                                Timestamp.valueOf(filter.getValue().toString())));
                        break;
                    default:
                        predicates.add(cb.like(mle.<String>get(filter.getKey()), (String) filter.getValue()));
                        break;
                    }
                }
            } else {
                predicates.add(cb.equal(mle.<String>get(filter.getKey()), filter.getValue()));
            }
        }
    }
    cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
    if (column != null) {
        if (asc) {
            cq.orderBy(cb.asc(mle.get(column)));
        } else {
            cq.orderBy(cb.desc(mle.get(column)));
        }

    }
    final TypedQuery<MessageLogEntry> query = this.em.createQuery(cq);
    query.setFirstResult(from);
    query.setMaxResults(max);
    return query.getResultList();
}

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

public Region getRegionByCodeOrName(final String code) {
    final CriteriaBuilder criteriaBuilder = this.entityManager.getCriteriaBuilder();

    final CriteriaQuery<JpaRegionImpl> c = criteriaBuilder.createQuery(JpaRegionImpl.class);
    c.distinct(true);//from   w  ww  .  ja  v  a2s. c  o  m
    final Root<JpaRegionImpl> region = c.from(JpaRegionImpl.class);
    c.where(criteriaBuilder.or(criteriaBuilder.equal(region.get(JpaRegionImpl_.code), code),
            criteriaBuilder.like(region.get(JpaRegionImpl_.name), code)));

    try {
        return this.entityManager.createQuery(c).getSingleResult();
    } catch (final Exception e) {
        log.debug(e.getMessage(), e);
        return null;
    }
}

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);//from   w  ww  .j av a2s.c  o  m

    // 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.osiam.resource_server.storage.dao.ResourceDao.java

public <T extends ResourceEntity> SearchResult<T> search(Class<T> clazz, ParseTree filterTree, int count,
        int startIndex, String sortBy, String sortOrder, FilterParser<T> filterParser) {

    CriteriaBuilder cb = em.getCriteriaBuilder();

    CriteriaQuery<T> resourceQuery = cb.createQuery(clazz);
    Root<T> resourceRoot = resourceQuery.from(clazz);

    Subquery<Long> internalIdQuery = resourceQuery.subquery(Long.class);
    Root<T> internalIdRoot = internalIdQuery.from(clazz);
    internalIdQuery.select(internalIdRoot.get(ResourceEntity_.internalId));

    if (filterTree != null && filterTree.getChildCount() > 0) {
        Predicate predicate = filterParser.createPredicateAndJoin(filterTree, internalIdRoot);
        internalIdQuery.where(predicate);
    }/* www  .j a  va 2  s .  co m*/

    resourceQuery.select(resourceRoot)
            .where(cb.in(resourceRoot.get(ResourceEntity_.internalId)).value(internalIdQuery));

    // TODO: evaluate if a User-/GroupDao supplied default sortBy field is possible
    Expression<?> sortByField = resourceRoot.get(ResourceEntity_.id);

    if (sortBy != null && !sortBy.isEmpty()) {
        sortByField = filterParser.createSortByField(sortBy, resourceRoot);
    }

    // default order is ascending
    Order order = cb.asc(sortByField);

    if (sortOrder.equalsIgnoreCase("descending")) {
        order = cb.desc(sortByField);
    }

    resourceQuery.orderBy(order);

    TypedQuery<T> query = em.createQuery(resourceQuery);
    query.setFirstResult(startIndex);
    query.setMaxResults(count);

    List<T> results = query.getResultList();

    long totalResult = getTotalResults(clazz, internalIdQuery);

    return new SearchResult<>(results, totalResult);
}