Example usage for javax.persistence.criteria CriteriaBuilder createQuery

List of usage examples for javax.persistence.criteria CriteriaBuilder createQuery

Introduction

In this page you can find the example usage for javax.persistence.criteria CriteriaBuilder createQuery.

Prototype

<T> CriteriaQuery<T> createQuery(Class<T> resultClass);

Source Link

Document

Create a CriteriaQuery object with the specified result type.

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(// w ww  . j ava  2 s .  c  o  m
            //
            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.aimdek.ccm.dao.impl.TransactionRepositoryImpl.java

/**
 * {@inheritDoc}//  w  ww. j  a  va 2  s  .  com
 */
public List<Transaction> findTransactionsByStatementDateAndCreditCardId(Date startDate, Date endDate,
        long creditCardId) {

    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Transaction> query = builder.createQuery(Transaction.class);
    Root<Transaction> root = query.from(Transaction.class);
    query.select(root);
    Predicate date = builder.greaterThan(root.<Date>get(FIELD_CONSTANT_TRANSACTION_DATE), startDate);
    Predicate isCreditCardId = builder.equal(root.<String>get(FIELD_CONSTANT_CREDIT_CARD_ID), creditCardId);
    query.where(builder.and(date, isCreditCardId));
    return super.find(query);
}

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

/**
 * {@inheritDoc}//from www  . j a  va  2 s  . c o m
 */
public List<Transaction> getTransactions(int start, int limit, String sortField, String sortOrder,
        Map<String, Object> filters, long userId) {

    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Transaction> query = builder.createQuery(Transaction.class);
    Root<Transaction> root = query.from(Transaction.class);
    query.select(root);
    addSorting(sortField, sortOrder, query, builder, root);
    addFilterCriteria(userId, filters, builder, root, query);

    return entityManager.createQuery(query).setFirstResult(start).setMaxResults(limit).getResultList();

}

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

/**
 * {@inheritDoc}//from  w ww .j  a va  2s .  c o m
 */
public List<Transaction> searchTransaction(String searchTerm) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Transaction> query = builder.createQuery(Transaction.class);
    Root<Transaction> root = query.from(Transaction.class);
    query.select(root);
    Predicate customerName = builder.like(root.<String>get(FIELDCONSTANT_CUSTOMERNAME),
            MODULO + searchTerm + MODULO);
    Predicate creditCardNumber = builder.like(root.<String>get(FIELDCONSTANT_CARDNUMBER),
            MODULO + searchTerm + MODULO);
    Predicate description = builder.like(root.<String>get(FIELD_CONSTANT_DESCRIPTION),
            MODULO + searchTerm + MODULO);
    query.where(builder.or(customerName, creditCardNumber, description));
    return super.find(query);
}

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);//  w  w  w .  ja  v  a  2s. co  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:com.aimdek.ccm.dao.impl.TransactionRepositoryImpl.java

/**
 * {@inheritDoc}/*from   ww w  .  j ava2 s. com*/
 */
public Transaction findLastTransaction() {

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

}

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

@Override
@Transactional(propagation = Propagation.MANDATORY, readOnly = true)
public <E extends Entity<K>, K> long getCount(final Class<E> clazz) {
    final CriteriaBuilder builder = this.getCriteriaBuilder();
    final CriteriaQuery<Long> criteriaQuery = builder.createQuery(Long.class);
    final Root<E> from = criteriaQuery.from(clazz);

    final Expression<Long> count = builder.count(from);

    criteriaQuery.select(count);/*w  ww .j a v  a  2 s  .c  o  m*/

    return this.findSingle(criteriaQuery).longValue();
}

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

@Override
public List<T> find() {
    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);
    return query.getResultList();
}

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 2 s. c o  m
    return query.getResultList();
}

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

/**
 * TODO    ManyToMany//from  w ww.j av a 2 s.c  o 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;
}