Example usage for javax.persistence EntityManager getCriteriaBuilder

List of usage examples for javax.persistence EntityManager getCriteriaBuilder

Introduction

In this page you can find the example usage for javax.persistence EntityManager getCriteriaBuilder.

Prototype

public CriteriaBuilder getCriteriaBuilder();

Source Link

Document

Return an instance of CriteriaBuilder for the creation of CriteriaQuery objects.

Usage

From source file:com.creditcloud.common.entities.dao.AbstractReadDAO.java

public <K> T findBy(String fieldName, Object value, Class<K> valueClass) {
    EntityManager em = getEntityManager();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<T> cq = cb.createQuery(entityClass);
    Root<T> root = cq.from(entityClass);
    cq.select(root).where(cb.equal(root.get(fieldName).as(valueClass), value));
    List<T> list = em.createQuery(cq).getResultList();
    return list.isEmpty() ? null : list.get(0);
}

From source file:com.creditcloud.common.entities.dao.AbstractReadDAO.java

/**
 * count all entity/* www .  j a va  2  s.  c o  m*/
 *
 * @return
 */
public int count() {
    EntityManager em = getEntityManager();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery cq = cb.createQuery();
    Root<T> rt = cq.from(entityClass);
    cq.select(cb.count(rt));
    Query q = em.createQuery(cq);
    Object result = q.getSingleResult();
    return result == null ? 0 : ((Long) result).intValue();
}

From source file:edu.sabanciuniv.sentilab.sare.models.base.documentStore.PersistentDocumentStore.java

/**
 * Gets identifiers of documents in this store.
 * @param em the {@link EntityManager} to get the documents from.
 * @return an {@link Iterable} of document identifiers.
 *///from   ww  w .  j  av a2  s  . com
public Iterable<byte[]> getDocumentIds(EntityManager em) {
    Validate.notNull(em, CannedMessages.NULL_ARGUMENT, "em");

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<byte[]> cq = cb.createQuery(byte[].class);
    Root<PersistentDocument> doc = cq.from(PersistentDocument.class);
    cq.multiselect(doc.get("id"))
            .where(cb.equal(doc.get("store"), cb.parameter(PersistentDocumentStore.class, "store")));
    TypedQuery<byte[]> tq = em.createQuery(cq);
    tq.setParameter("store", this);
    return tq.getResultList();
}

From source file:ru.savvy.jpafilterbuilder.FilterCriteriaBuilder.java

/**
 * Creates new instance from existing query
 *
 * @param em//  w w  w  .ja  v  a2s  .  c  om
 * @param query
 */
public FilterCriteriaBuilder(EntityManager em, CriteriaQuery<T> query) {
    this.cb = em.getCriteriaBuilder();
    this.clazz = query.getResultType();
    //this.query = query;
    this.options = EnumSet.noneOf(Option.class);
    this.pb = new PredicateBuilder(cb, options);
    this.metamodel = em.getMetamodel();
    //        Set<Root<?>> roots = query.getRoots();
    //        for (Root<?> r : roots) {
    //            if (r.getJavaType().equals(this.clazz)) {
    //                this.root = (Root<T>) r;
    //                break;
    //            }
    //        }
    //        if (this.root == null) {
    //            this.root = query.from(this.clazz);
    //        }
}

From source file:com.creditcloud.common.entities.dao.AbstractReadDAO.java

/**
 * count entity by ParamInfo/*from   w w w  .j a v  a  2  s .c  o m*/
 *
 * @param paramInfo
 * @return
 */
public int count(ParamInfo paramInfo) {
    EntityManager em = getEntityManager();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery cq = cb.createQuery(entityClass);
    Root<T> userRoot = cq.from(entityClass);
    cq.select(cb.count(userRoot));

    //build query for paramInfo
    if (paramInfo != null) {
        Set<Predicate> andCriteria = new HashSet();
        Set<Predicate> orCriteria = new HashSet();

        for (ParamItem item : paramInfo.getParamItems()) {
            Predicate predicate;
            if (item.getValue() instanceof String) {
                //fuzy search for string
                String regExp = "%" + item.getValue() + "%";
                predicate = cb.like((Expression) (userRoot.get(item.getFieldName())), regExp);
            } else {
                predicate = cb.equal((userRoot.get(item.getFieldName())), item.getValue());
            }

            switch (item.getOperator()) {
            case AND:
                andCriteria.add(predicate);
                break;
            case OR:
                orCriteria.add(predicate);
                break;
            }
        }
        if (orCriteria.size() > 0) {
            Predicate or = cb.or(orCriteria.toArray(new Predicate[orCriteria.size()]));
            andCriteria.add(or);
        }
        if (andCriteria.size() > 0) {
            Predicate and = cb.and(andCriteria.toArray(new Predicate[andCriteria.size()]));
            cq.where(and);
        }
    }

    TypedQuery<Long> query = em.createQuery(cq);
    Long result = query.getSingleResult();
    return result == null ? 0 : result.intValue();
}

From source file:fr.amapj.service.services.authentification.PasswordManager.java

/**
 * Retrouve l'utilisateur avec ce resetPasswordSald
 * Retourne null si non trouv ou autre problme
 *//* w  ww .  ja  v  a2  s  .c o m*/
@DbRead
public Utilisateur findUserWithResetPassword(String resetPasswordSalt) {
    EntityManager em = TransactionHelper.getEm();

    if ((resetPasswordSalt == null) || resetPasswordSalt.equals("")) {
        return null;
    }

    CriteriaBuilder cb = em.getCriteriaBuilder();

    CriteriaQuery<Utilisateur> cq = cb.createQuery(Utilisateur.class);
    Root<Utilisateur> root = cq.from(Utilisateur.class);

    // On ajoute la condition where 
    cq.where(cb.equal(root.get(Utilisateur.P.RESETPASSWORDSALT.prop()), resetPasswordSalt));

    List<Utilisateur> us = em.createQuery(cq).getResultList();
    if (us.size() == 0) {
        return null;
    }

    if (us.size() > 1) {
        logger.warn("Il y a plusieurs utilisateurs avec le salt " + resetPasswordSalt);
        return null;
    }

    Utilisateur u = us.get(0);

    if (u.getEtatUtilisateur() == EtatUtilisateur.INACTIF) {
        return null;
    }

    return u;
}

From source file:ru.savvy.jpafilterbuilder.FilterCriteriaBuilder.java

/**
 * Creates new instance. Class/*from ww w.  ja  va 2  s .  com*/
 *
 * @param em
 * @param clazz must be JPA Entity annotated
 */
public FilterCriteriaBuilder(EntityManager em, Class<T> clazz) {
    this.clazz = clazz;
    this.cb = em.getCriteriaBuilder();
    //this.query = cb.createQuery(clazz);
    //this.root = query.from(clazz);
    this.options = EnumSet.noneOf(Option.class);
    this.pb = new PredicateBuilder(cb, options);
    this.metamodel = em.getMetamodel();
}

From source file:com.creditcloud.common.entities.dao.AbstractReadDAO.java

/**
 * list entity by CriteriaInfo/*  w ww  .  j a  va 2s .c  o m*/
 *
 * @param criteriaInfo
 * @return PagedResult
 */
public PagedResult<T> list(CriteriaInfo criteriaInfo) {
    EntityManager em = getEntityManager();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery cq = cb.createQuery(entityClass);
    Root<T> userRoot = cq.from(entityClass);
    cq.select(userRoot);
    ParamInfo paramInfo = criteriaInfo.getParamInfo();
    PageInfo pageInfo = criteriaInfo.getPageInfo();
    SortInfo sortInfo = criteriaInfo.getSortInfo();

    //build query for paramInfo
    if (paramInfo != null) {
        Set<Predicate> andCriteria = new HashSet();
        Set<Predicate> orCriteria = new HashSet();

        for (ParamItem item : paramInfo.getParamItems()) {
            Predicate predicate;
            if (item.getValue() instanceof String) {
                //fuzy search for string
                String regExp = "%" + item.getValue() + "%";
                predicate = cb.like((Expression) (userRoot.get(item.getFieldName())), regExp);
            } else {
                predicate = cb.equal((userRoot.get(item.getFieldName())), item.getValue());
            }

            switch (item.getOperator()) {
            case AND:
                andCriteria.add(predicate);
                break;
            case OR:
                orCriteria.add(predicate);
                break;
            }
        }
        if (orCriteria.size() > 0) {
            Predicate or = cb.or(orCriteria.toArray(new Predicate[orCriteria.size()]));
            andCriteria.add(or);
        }
        if (andCriteria.size() > 0) {
            Predicate and = cb.and(andCriteria.toArray(new Predicate[andCriteria.size()]));
            cq.where(and);
        }
    }

    //build query for sortInfo
    Set<Order> orderPredicate = new HashSet<>();
    if (sortInfo != null) {
        for (SortItem item : sortInfo.getSortItems()) {
            if (item.isDescending()) {
                orderPredicate.add(cb.desc(userRoot.get(item.getFieldName())));
            } else {
                orderPredicate.add(cb.asc(userRoot.get(item.getFieldName())));
            }
        }
    }
    if (orderPredicate.size() > 0) {
        cq.orderBy(orderPredicate.toArray(new Order[orderPredicate.size()]));
    }

    TypedQuery<T> query = em.createQuery(cq);
    //set result range
    if (pageInfo != null) {
        query.setFirstResult(pageInfo.getOffset());
        query.setMaxResults(pageInfo.getSize());
    }

    int totalSize;
    if (paramInfo != null && paramInfo.getParamItems().size() > 0) {
        totalSize = count(paramInfo);
    } else {
        totalSize = count();
    }

    return new PagedResult(query.getResultList(), totalSize);
}

From source file:in.bookmylab.jpa.JpaDAO.java

public List<ResourceBooking> searchResourceBooking(BookingSearchInput si) {
    EntityManager em = emf.createEntityManager();
    try {//from w w w  .  j  av  a  2  s  . c  o  m
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<ResourceBooking> cq = cb.createQuery(ResourceBooking.class);
        Root<ResourceBooking> s = cq.from(ResourceBooking.class);
        List<Predicate> pred = new ArrayList<Predicate>();
        if (si.userId != null) {
            pred.add(cb.equal(s.<User>get("user").<Integer>get("userId"), si.userId));
        }
        if (si.bookingDateFrom != null) {
            pred.add(cb.greaterThanOrEqualTo(s.<Date>get("bookingDate"), si.bookingDateFrom));
        }
        if (si.bookingDateTo != null) {
            pred.add(cb.lessThanOrEqualTo(s.<Date>get("bookingDate"), si.bookingDateTo));
        }
        if (!StringUtils.isEmpty(si.lab)) {
            pred.add(cb.equal(s.<String>get("lab"), si.lab));
        }
        if (!StringUtils.isEmpty(si.status)) {
            pred.add(cb.equal(s.<String>get("status"), si.status));
        }
        cq.select(s).where(pred.toArray(new Predicate[] {}));
        return em.createQuery(cq).getResultList();
    } finally {
        em.close();
    }
}

From source file:org.apache.openejb.util.proxy.QueryProxy.java

private <T> Query createFinderQuery(final EntityManager entityManager, final String methodName,
        final Class<T> entityType, final Object[] args) {
    final List<String> conditions = parseMethodName(methodName);

    final EntityType<T> et = entityManager.getMetamodel().entity(entityType);
    final CriteriaBuilder cb = entityManager.getCriteriaBuilder();

    CriteriaQuery<Object> query = cb.createQuery();
    final Root<T> from = query.from(entityType);
    query = query.select(from);/*from  w w  w .  j a  v  a 2s  .co  m*/

    int i = 0;
    Predicate where = null;
    for (final String condition : conditions) {
        final SingularAttribute<? super T, ?> attribute = et.getSingularAttribute(condition);
        final Path<?> path = from.get(attribute);
        final Class<?> javaType = attribute.getType().getJavaType();

        final Predicate currentClause;
        if (javaType.equals(String.class)) {
            currentClause = cb.like((Expression<String>) path, (String) args[i++]);
        } else if (Number.class.isAssignableFrom(javaType) || javaType.isPrimitive()) {
            currentClause = cb.equal(path, args[i++]);
        } else {
            LOGGER.warning("field " + condition + " not found, ignoring");
            continue;
        }

        if (where == null) {
            where = currentClause;
        } else {
            where = cb.and(where, currentClause);
        }
    }

    if (where != null) {
        query = query.where(where);
    }

    // pagination
    final TypedQuery<?> emQuery = entityManager.createQuery(query);
    if (args != null && args.length == conditions.size() + 2 && isInt(args[args.length - 2].getClass())
            && isInt(args[args.length - 1].getClass())) {
        final int first = (Integer) args[args.length - 2];
        final int max = (Integer) args[args.length - 1];

        emQuery.setFirstResult(first);
        emQuery.setMaxResults(max);
    }

    return emQuery;
}