Example usage for javax.persistence.criteria Root get

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

Introduction

In this page you can find the example usage for javax.persistence.criteria Root 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.sloth.persistence.impl.ObservationDaoImpl.java

@Override
public Collection<Observation> getByCategorie(Categorie c)
        throws NullPointerException, IllegalArgumentException {
    if (c == null) {
        throw new NullPointerException();
    }/*from   ww w. jav  a  2s  .c  om*/
    if (c.isNew()) {
        throw new IllegalArgumentException();
    }
    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
    CriteriaQuery<Observation> cq = cb.createQuery(Observation.class);
    Root<Observation> o = cq.from(Observation.class);
    cq.select(o).where(cb.equal(o.get(Observation_.categorie), c));
    Collection<Observation> result = getEntityManager().createQuery(cq).getResultList();
    logger.info("{} Observations in Categorie {}.", result.size(), c);
    return result;
}

From source file:org.sloth.persistence.impl.ObservationDaoImpl.java

@Override
public List<Observation> getNewestObservations(int count) {
    if (count <= 0) {
        return new LinkedList<Observation>();
    }//from   www  .j a  va  2 s .c  o  m
    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
    CriteriaQuery<Observation> cq = cb.createQuery(Observation.class);
    Root<Observation> o = cq.from(Observation.class);
    cq.select(o).orderBy(cb.desc(o.get(Observation_.creationDate)));
    List<Observation> result = getEntityManager().createQuery(cq).setMaxResults(count).getResultList();

    if (result.size() < count) {
        logger.info("Only {} Observations in the database", result.size());
    } else {
        logger.info("Found the {} last Observations", result.size());
    }
    return result;

}

From source file:net.dontdrinkandroot.persistence.dao.TypedJpaDao.java

@Override
@Transactional(propagation = Propagation.MANDATORY, readOnly = true)
public List<E> findAll(final SingularAttribute<? super E, ?> attribute, final boolean asc) {
    final CriteriaBuilder builder = this.getCriteriaBuilder();
    final CriteriaQuery<E> criteriaQuery = builder.createQuery(this.entityClass);
    final Root<E> from = criteriaQuery.from(this.entityClass);

    if (asc) {//ww w  . ja v a 2  s .c o  m
        criteriaQuery.orderBy(builder.asc(from.get(attribute)));
    } else {
        criteriaQuery.orderBy(builder.desc(from.get(attribute)));
    }

    return this.find(criteriaQuery);
}

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);//w  w w. j a  v a2s. co 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:org.osiam.resource_server.storage.dao.ResourceDao.java

/**
 * Retrieves a single {@link ResourceEntity} by the given attribute and value.
 * /*from  w w  w  . j av a  2 s.  c o m*/
 * @param attribute
 *        The attribute of the resource entity to retrieve it by
 * @param value
 *        The value of the attribute to compare it to
 * @param clazz
 *        The concrete resource entity class to retrieve (may also be {@link ResourceEntity})
 * @return The matching {@link ResourceEntity}
 * @throws ResourceNotFoundException
 *         If no {@link ResourceEntity} could be found
 * @throws OsiamException
 *         If more than 1 {@link ResourceEntity} was found
 */
public <T extends ResourceEntity, V> T getByAttribute(SingularAttribute<? super T, V> attribute, V value,
        Class<T> clazz) {

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<T> cq = cb.createQuery(clazz);
    Root<T> resource = cq.from(clazz);

    cq.select(resource).where(cb.equal(resource.get(attribute), value));

    TypedQuery<T> q = em.createQuery(cq);

    try {
        return q.getSingleResult();
    } catch (NoResultException nre) {
        throw new ResourceNotFoundException(
                String.format("Resource with attribute '%s' set to '%s' not found", attribute.getName(), value),
                nre);
    } catch (NonUniqueResultException nure) {
        throw new OsiamException(String.format("Muliple resources with attribute '%s' set to '%s' found",
                attribute.getName(), value), nure);
    }
}

From source file:com.fantasy.stataggregator.workers.GameDataRetrieverTask.java

/**
 * Sets the statistical year to be requested.
 *
 * @param year//from   w  w w.  ja  v a2  s.  com
 * @throws java.text.ParseException
 */
@Override
public void setYear(int year) throws ParseException {
    if (Objects.nonNull(ctx)) {
        this.year = year;
        isTaskComplete = false;
        GameScheduleRepository gsr = ctx.getBean(GameScheduleRepository.class);
        if (year == Integer.MAX_VALUE) {
            schedules = gsr.findAll();
        } else {
            SimpleDateFormat sdf = ctx.getBean(SimpleDateFormat.class);
            sdf.applyLocalizedPattern("yyyyMMdd");

            Date min = sdf.parse(year + START_OF_YEAR);
            Date max = sdf.parse(year + END_OF_YEAR);

            CriteriaBuilder cb = gsr.getCriteriaBuilder();
            CriteriaQuery<GameSchedule> cq = gsr.getCriteriaQuery();
            Root<GameSchedule> gameSchedule = gsr.getRoot();
            cq.select(gameSchedule).where(cb.between(gameSchedule.get(GameSchedule_.gamedate), min, max))
                    .orderBy(cb.asc(gameSchedule.get(GameSchedule_.gameid)));

            schedules = gsr.getCriteriaList(cq);
            System.out.println(schedules.size());
        }
    }
}

From source file:net.groupbuy.dao.impl.CouponCodeDaoImpl.java

public Page<CouponCode> findPage(Member member, Pageable pageable) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<CouponCode> criteriaQuery = criteriaBuilder.createQuery(CouponCode.class);
    Root<CouponCode> root = criteriaQuery.from(CouponCode.class);
    criteriaQuery.select(root);//from www.  j  ava2s  .  c o m
    if (member != null) {
        criteriaQuery.where(criteriaBuilder.equal(root.get("member"), member));
    }
    return super.findPage(criteriaQuery, pageable);
}

From source file:com.aimdek.ccm.dao.impl.StatementRepositoryImpl.java

/**
 * {@inheritDoc}//from   ww w. j ava 2s  .co m
 */
public Statement findLastStatement() {

    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Statement> query = builder.createQuery(Statement.class);
    Root<Statement> root = query.from(Statement.class);
    query.select(root);
    query.orderBy(builder.desc(root.get(FIELD_CONSTANT_STATEMENT_DATE)));
    try {
        return entityManager.createQuery(query).setMaxResults(1).getSingleResult();
    } catch (NoResultException e) {
        LOGGER.error("Error while retrieving last statement", e);
    }
    return null;
}

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

/**
 * TODO    ManyToMany/*from  w w w.  j a v  a2s .  co  m*/
 * @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:net.shopxx.dao.impl.CouponCodeDaoImpl.java

public Long count(Coupon coupon, Member member, Boolean hasBegun, Boolean hasExpired, Boolean isUsed) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<CouponCode> criteriaQuery = criteriaBuilder.createQuery(CouponCode.class);
    Root<CouponCode> root = criteriaQuery.from(CouponCode.class);
    criteriaQuery.select(root);/*w w w.  j  a  v  a2s. c  o m*/
    Predicate restrictions = criteriaBuilder.conjunction();
    Path<Coupon> couponPath = root.get("coupon");
    if (coupon != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(couponPath, coupon));
    }
    if (member != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("member"), member));
    }
    if (hasBegun != null) {
        if (hasBegun) {
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.or(couponPath.get("beginDate").isNull(),
                            criteriaBuilder.lessThanOrEqualTo(couponPath.<Date>get("beginDate"), new Date())));
        } else {
            restrictions = criteriaBuilder.and(restrictions, couponPath.get("beginDate").isNotNull(),
                    criteriaBuilder.greaterThan(couponPath.<Date>get("beginDate"), new Date()));
        }
    }
    if (hasExpired != null) {
        if (hasExpired) {
            restrictions = criteriaBuilder.and(restrictions, couponPath.get("endDate").isNotNull(),
                    criteriaBuilder.lessThanOrEqualTo(couponPath.<Date>get("endDate"), new Date()));
        } else {
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.or(couponPath.get("endDate").isNull(),
                            criteriaBuilder.greaterThan(couponPath.<Date>get("endDate"), new Date())));
        }
    }
    if (isUsed != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isUsed"), isUsed));
    }
    criteriaQuery.where(restrictions);
    return super.count(criteriaQuery, null);
}