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:eu.domibus.common.dao.ErrorLogDao.java

public List<ErrorLogEntry> findPaged(int from, int max, String column, boolean asc,
        HashMap<String, Object> filters) {
    CriteriaBuilder cb = this.em.getCriteriaBuilder();
    CriteriaQuery<ErrorLogEntry> cq = cb.createQuery(ErrorLogEntry.class);
    Root<ErrorLogEntry> ele = cq.from(ErrorLogEntry.class);
    cq.select(ele);//from  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 "":
                        break;
                    case "timestampFrom":
                        predicates.add(cb.greaterThanOrEqualTo(ele.<Date>get("timestamp"),
                                Timestamp.valueOf(filter.getValue().toString())));
                        break;
                    case "timestampTo":
                        predicates.add(cb.lessThanOrEqualTo(ele.<Date>get("timestamp"),
                                Timestamp.valueOf(filter.getValue().toString())));
                        break;
                    case "notifiedFrom":
                        predicates.add(cb.greaterThanOrEqualTo(ele.<Date>get("notified"),
                                Timestamp.valueOf(filter.getValue().toString())));
                        break;
                    case "notifiedTo":
                        predicates.add(cb.lessThanOrEqualTo(ele.<Date>get("notified"),
                                Timestamp.valueOf(filter.getValue().toString())));
                        break;
                    default:
                        predicates.add(cb.like(ele.<String>get(filter.getKey()), (String) filter.getValue()));
                        break;
                    }
                }
            } else {
                predicates.add(cb.equal(ele.<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(ele.get(column)));
        } else {
            cq.orderBy(cb.desc(ele.get(column)));
        }

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

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

@Override
public User getByMail(String mail) {
    if (mail == null) {
        throw new NullPointerException();
    }/*from  w ww  .j a  v a 2  s  . c o m*/
    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
    CriteriaQuery<User> cq = cb.createQuery(User.class);
    Root<User> user = cq.from(User.class);
    cq.select(user).where(cb.equal(user.get(User_.mail), mail));
    User result = null;
    try {
        result = getEntityManager().createQuery(cq).getSingleResult();
    } catch (NoResultException e) {
        logger.info("User with address {} not found", mail);
    } catch (NonUniqueResultException e) {
        logger.warn("Corrupt Database", e);
    }
    return result;
}

From source file:com.samples.platform.serviceprovider.library.internal.dao.PlatformDao.java

/**
 * @param ISBN//from  ww w.j  a  va 2  s  .c  om
 *            the ISBN of the book to find.
 * @return the {@link BookType}.
 */
@Transactional(value = PersistenceConfig.TRANSACTION_MANAGER_NAME, propagation = Propagation.REQUIRED)
public BookType getBookByISBN(final String ISBN) {
    BookType m = null;
    if (ISBN == null) {
        this.logger.debug("getBookByISBN: ISBN is null.");
    } else {
        CriteriaBuilder cb = this.em.getCriteriaBuilder();
        CriteriaQuery<BookType> q = cb.createQuery(BookType.class);
        Root<BookType> c = q.from(BookType.class);
        q.where(cb.equal(c.<String>get(BookType_.ISBN), ISBN));
        TypedQuery<BookType> typedQuery = this.em.createQuery(q);
        try {
            m = typedQuery.getSingleResult();
            this.logger.debug("getBookByISBN: " + ToStringBuilder.reflectionToString(m));
        } catch (NoResultException e) {
            this.logger.debug("getBookByISBN: non value found for ISBN=" + ISBN);
            m = null;
        }
    }
    return m;
}

From source file:com.samples.platform.serviceprovider.library.internal.dao.PlatformDao.java

/**
 * @param uuid//from  w  w  w  .ja  v  a  2  s  . c  o m
 *            the id of the book to find.
 * @return the {@link BookType}.
 */
@Transactional(value = PersistenceConfig.TRANSACTION_MANAGER_NAME, propagation = Propagation.REQUIRED)
public BookType getBookById(final String uuid) {
    BookType m = null;
    if (uuid == null) {
        this.logger.debug("getBookById: UUID is null.");
    } else {
        CriteriaBuilder cb = this.em.getCriteriaBuilder();
        CriteriaQuery<BookType> q = cb.createQuery(BookType.class);
        Root<BookType> c = q.from(BookType.class);
        q.where(cb.equal(c.<String>get(EntityType_.UUID), uuid));
        TypedQuery<BookType> typedQuery = this.em.createQuery(q);
        try {
            m = typedQuery.getSingleResult();
            this.logger.debug("getBookByISBN: " + ToStringBuilder.reflectionToString(m));
        } catch (NoResultException e) {
            this.logger.debug("getBookByISBN: non value found for id=" + uuid);
            m = null;
        }
    }
    return m;
}

From source file:de.ks.idnadrev.information.view.InformationOverviewDS.java

private List<InformationPreviewItem> getResults(String name, List<String> tagNames, Category category,
        EntityManager em, CriteriaBuilder builder, Class<? extends Information<?>> clazz) {
    CriteriaQuery<InformationPreviewItem> query = builder.createQuery(InformationPreviewItem.class);
    Root<? extends Information<?>> root = query.from(clazz);

    ArrayList<Predicate> filters = new ArrayList<>();
    if (!name.isEmpty()) {
        filters.add(builder.like(builder.lower(root.<String>get(KEY_NAME)), name));
    }/*from w w w.j  a v a  2  s . co  m*/
    if (!tagNames.isEmpty()) {
        List<Tag> tags = getTags(tagNames, em);
        SetJoin<TextInfo, Tag> tagJoin = root.joinSet(KEY_TAGS);
        filters.add(tagJoin.in(tags));
    }
    if (category != null) {
        filters.add(builder.equal(root.get(KEY_CATEGORY), category));
    }
    query.distinct(true);

    query.where(filters.toArray(new Predicate[filters.size()]));
    query.select(
            builder.construct(InformationPreviewItem.class, root.get(KEY_NAME), root.get(KEY_CREATIONTIME)));
    List<InformationPreviewItem> resultList = em.createQuery(query).getResultList();
    return resultList;
}

From source file:com.moderndrummer.data.MemberDaoImpl.java

@Override
public boolean isValidUser(String userName, String password) {
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Member> criteria = builder.createQuery(Member.class);
    Root<Member> member = criteria.from(Member.class);

    criteria.select(member).where(builder.equal(member.get("name"), userName))
            .where(builder.equal(member.get("password"), password));
    try {/*from  w  w  w.  j a  v a2  s  .c o  m*/

        Member validMember = em.createQuery(criteria).setMaxResults(1).getSingleResult();
        return ObjectUtil.verifyMemberExists(validMember);

    } catch (NoResultException e) {
        return false;
    }

}

From source file:br.nom.abdon.gastoso.dal.FatosDao.java

public List<Fato> listar(final EntityManager em, final FiltroFatos filtroFatos) {

    final CriteriaBuilder cb = em.getCriteriaBuilder();

    final CriteriaQuery<Fato> q = cb.createQuery(Fato.class);

    final Root<Fato> root = q.from(Fato.class);

    final List<Predicate> where = new LinkedList<>();
    final Map<String, Object> params = new HashMap<>();

    buildQuery(cb, filtroFatos, root, where, params);

    trataOrdenacao(filtroFatos, root, cb, q);

    return DalUtil.prepareAndRunQuery(em, q, where, params, filtroFatos.getPaginacao());
}

From source file:com.aimdek.ccm.dao.impl.test.StatementDaoImplTest.java

/**
 * Test find filter statement./* w  ww  . j  a va2s  .  c om*/
 */
@Test
public void testFindFilterStatement() {

    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Statement> query = builder.createQuery(Statement.class);
    Root<Statement> root = query.from(Statement.class);
    query.select(root);
    int limit = 4 - 2;
    List<Statement> statementList = entityManager.createQuery(query).setFirstResult(2).setMaxResults(limit)
            .getResultList();

    assertEquals(2, statementList.size());
}

From source file:com.aimdek.ccm.dao.impl.test.StatementDaoImplTest.java

/**
 * Test filtering./*from   ww  w.  j a v  a 2  s  .co  m*/
 */
@Test
public void testFiltering() {

    String cardNumber = "0008";
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Statement> query = builder.createQuery(Statement.class);
    Root<Statement> root = query.from(Statement.class);
    query.select(root);
    query.where(builder.like(root.<String>get(FIELDCONSTANT_CARDNUMBER), "%" + cardNumber));
    List<Statement> statementList = entityManager.createQuery(query).getResultList();

    assertEquals(4, statementList.size());
}

From source file:com.devicehive.dao.rdbms.UserDaoRdbmsImpl.java

@Override
public List<UserVO> list(String login, String loginPattern, Integer role, Integer status, String sortField,
        Boolean sortOrderAsc, Integer take, Integer skip) {
    CriteriaBuilder cb = criteriaBuilder();
    CriteriaQuery<User> cq = cb.createQuery(User.class);
    Root<User> from = cq.from(User.class);

    Predicate[] predicates = CriteriaHelper.userListPredicates(cb, from, ofNullable(login),
            ofNullable(loginPattern), ofNullable(role), ofNullable(status));
    cq.where(predicates);//from   www .j  ava  2 s  .c o  m
    CriteriaHelper.order(cb, cq, from, ofNullable(sortField), Boolean.TRUE.equals(sortOrderAsc));

    TypedQuery<User> query = createQuery(cq);
    cacheQuery(query, of(CacheConfig.refresh()));
    ofNullable(take).ifPresent(query::setMaxResults);
    ofNullable(skip).ifPresent(query::setFirstResult);
    return query.getResultList().stream().map(User::convertToVo).collect(Collectors.toList());
}