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.ocs.dynamo.dao.query.JpaQueryBuilder.java

/**
 * Creates a query to fetch an object based on a value of a unique property
 * //from www.j  a  va2 s.  c  o  m
 * @param entityManager
 *            the entity manager
 * @param entityClass
 *            the entity class
 * @param fetchJoins
 *            the fetch joins to include
 * @param propertyName
 *            name of the property to search on
 * @param value
 *            value of the property to search on
 * @return
 */
public static <T> CriteriaQuery<T> createUniquePropertyFetchQuery(EntityManager entityManager,
        Class<T> entityClass, FetchJoinInformation[] fetchJoins, String propertyName, Object value,
        boolean caseSensitive) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<T> cq = builder.createQuery(entityClass);
    Root<T> root = cq.from(entityClass);

    addFetchJoinInformation(root, fetchJoins);

    Predicate equals = null;
    if (value instanceof String && !caseSensitive) {
        equals = builder.equal(builder.upper(root.get(propertyName).as(String.class)),
                ((String) value).toUpperCase());
    } else {
        equals = builder.equal(root.get(propertyName), value);
    }
    cq.where(equals);
    cq.distinct(true);

    return cq;
}

From source file:sf.net.experimaestro.scheduler.Resource.java

/**
 * Get a resource by locator//from   w ww.j ava  2s.c o  m
 *
 * @param em   The current entity manager
 * @param path The path of the resource
 * @return The resource or null if there is no such resource
 */
public static Resource getByLocator(EntityManager em, String path) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Resource> cq = cb.createQuery(Resource.class);
    Root<Resource> root = cq.from(Resource.class);
    cq.where(root.get("locator").in(cb.parameter(String.class, "locator")));

    TypedQuery<Resource> query = em.createQuery(cq);
    query.setParameter("locator", path);
    List<Resource> result = query.getResultList();
    assert result.size() <= 1;

    if (result.isEmpty())
        return null;

    return result.get(0);
}

From source file:org.ibankapp.base.persistence.validation.validator.UniqueValidator.java

@SuppressWarnings("unchecked")
public static <T> void validate(T bean, EntityManager em) {

    EntityInformation ei = new EntityInformation(bean.getClass(), em.getMetamodel());

    Iterable<String> idAttributeNames = ei.getIdAttributeNames();

    List<Unique> uniqueList = new ArrayList<>();

    if (bean.getClass().isAnnotationPresent(Uniques.class)) {
        Uniques uniques = bean.getClass().getAnnotation(Uniques.class);
        Collections.addAll(uniqueList, uniques.constraints());
    }//from   ww  w.  j av a 2 s . co  m

    if (bean.getClass().isAnnotationPresent(Unique.class)) {
        uniqueList.add(bean.getClass().getAnnotation(Unique.class));
    }

    for (Unique unique : uniqueList) {

        String[] properties = unique.properties();

        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<?> c = cb.createQuery(bean.getClass());

        Root<?> root = c.from(bean.getClass());

        Predicate condition = cb.conjunction();

        try {

            for (String idAttributeName : idAttributeNames) {
                condition = cb.and(condition, cb.notEqual(root.get(idAttributeName),
                        PropertyUtils.getProperty(bean, idAttributeName)));
            }

            for (String property : properties) {
                condition = cb.and(condition,
                        cb.equal(root.get(property), PropertyUtils.getProperty(bean, property)));
            }
        } catch (Exception e) {
            throw new BaseException("E-BASE-000001", e.getMessage()).initCause(e);
        }

        c.where(condition);

        int count = em.createQuery(c).getResultList().size();

        if (count != 0) {
            throw new BaseException("E-BASE-000008", unique.message());
        }
    }
}

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

protected List<Tag> getTags(List<String> tagNames, EntityManager em) {
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Tag> query = builder.createQuery(Tag.class);
    Root<Tag> root = query.from(Tag.class);
    Path<String> namePath = root.get(KEY_NAME);
    query.select(root);//from   w  w w.  jav a 2 s.  c  o  m
    query.where(namePath.in(tagNames));

    return em.createQuery(query).getResultList();
}

From source file:vn.edu.vnuk.tasks_jpa.dao.TaskDao.java

public List<Task> read() throws SQLException {

    EntityManager manager = getEntityManager();

    CriteriaQuery criteria = manager.getCriteriaBuilder().createQuery();
    criteria.select(criteria.from(Task.class));

    return manager.createQuery(criteria).getResultList();

}

From source file:ispok.dao.TournamentHibernateJpaDao.java

@Override
public Long getCount(Map<String, Object> filters) {

    EntityManager em = getEntityManager();

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Long> cq = cb.createQuery(Long.class);
    Root<Tournament> t = cq.from(Tournament.class);

    cq.select(cb.count(t));//from  w  w w . j a  va2 s  . c  o  m

    TypedQuery<Long> tq = em.createQuery(cq);
    return tq.getSingleResult();
}

From source file:com.soen.ebanking.dao.ObjectDao.java

public List getAllObjects(Class<T> ClassName, String tableName) {
    EntityManager em = this.getEMF().createEntityManager();
    CriteriaBuilder qb = em.getCriteriaBuilder();
    CriteriaQuery<T> query = qb.createQuery(ClassName);
    //Root<T> entities = query.from(ClassName);
    List<T> result = em.createQuery(query).getResultList();

    return result;
}

From source file:com.sixsq.slipstream.persistence.Run.java

public static int viewListCount(User user, String moduleResourceUri, String cloudServiceName)
        throws ConfigurationException, ValidationException {
    int count = 0;
    EntityManager em = PersistenceUtil.createEntityManager();
    try {// www .  jav  a2  s .  com
        CriteriaBuilder builder = em.getCriteriaBuilder();
        CriteriaQuery<Long> critQuery = builder.createQuery(Long.class);
        Root<Run> rootQuery = critQuery.from(Run.class);
        critQuery.select(builder.count(rootQuery));
        Predicate where = viewListCommonQueryOptions(builder, rootQuery, user, moduleResourceUri,
                cloudServiceName);
        if (where != null) {
            critQuery.where(where);
        }
        TypedQuery<Long> query = em.createQuery(critQuery);
        count = (int) (long) query.getSingleResult();
    } finally {
        em.close();
    }
    return count;
}

From source file:com.sixsq.slipstream.persistence.Run.java

public static List<RunView> viewList(User user, String moduleResourceUri, Integer offset, Integer limit,
        String cloudServiceName) throws ConfigurationException, ValidationException {
    List<RunView> views = null;
    EntityManager em = PersistenceUtil.createEntityManager();
    try {/*from w  ww  . ja va2 s  . c  o  m*/
        CriteriaBuilder builder = em.getCriteriaBuilder();
        CriteriaQuery<Run> critQuery = builder.createQuery(Run.class);
        Root<Run> rootQuery = critQuery.from(Run.class);
        critQuery.select(rootQuery);
        Predicate where = viewListCommonQueryOptions(builder, rootQuery, user, moduleResourceUri,
                cloudServiceName);
        if (where != null) {
            critQuery.where(where);
        }
        critQuery.orderBy(builder.desc(rootQuery.get("startTime")));
        TypedQuery<Run> query = em.createQuery(critQuery);
        if (offset != null) {
            query.setFirstResult(offset);
        }
        query.setMaxResults((limit != null) ? limit : DEFAULT_LIMIT);
        List<Run> runs = query.getResultList();
        views = convertRunsToRunViews(runs);
    } finally {
        em.close();
    }
    return views;
}

From source file:de.egore911.persistence.selector.AbstractSelector.java

private TypedQuery<T> buildQuery() {
    EntityManager em = EntityManagerUtil.getEntityManager();
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<T> cq = builder.createQuery(getEntityClass());
    Root<T> from = cq.from(getEntityClass());
    List<Predicate> predicates = generatePredicateList(builder, from, cq);
    cq.where(predicates.toArray(new Predicate[predicates.size()]));
    cq.orderBy(generateOrderList(builder, from));
    cq.select(from);//  www.  j  a  va2s .com
    return em.createQuery(cq);
}