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:name.marcelomorales.siqisiqi.openjpa.impl.OrmFinderImpl.java

@Override
@TransactionAttribute/*  w w w .j  ava 2 s .  c  o m*/
public long countByAttribute(String attributeName, Object attributeValue) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Long> q = cb.createQuery(Long.class);

    Root<T> p = q.from(persistentClass);
    final Expression<Long> count = newCountExpression(cb, p);
    q.select(count);
    q.where(cb.equal(p.get(attributeName), attributeValue));

    try {
        return entityManager.createQuery(q).getSingleResult();
    } catch (NoResultException e) {
        return 0;
    }
}

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.aimdek.ccm.dao.impl.StatementRepositoryImpl.java

/**
 * Adds the filter criteria./*  w ww  . jav a  2  s  .c o  m*/
 *
 * @param userId
 *            the user id
 * @param filters
 *            the filters
 * @param builder
 *            the builder
 * @param root
 *            the root
 * @param query
 *            the query
 */
private void addFilterCriteria(long userId, Map<String, Object> filters, CriteriaBuilder builder,
        Root<Statement> root, CriteriaQuery query) {

    List<Predicate> predicates = new ArrayList<Predicate>();
    if (!filters.isEmpty()) {
        for (Entry<String, Object> entry : filters.entrySet()) {
            if (CommonUtil.isNotNull(root.get(entry.getKey()))) {
                predicates.add(builder.like(root.<String>get(entry.getKey()), entry.getValue() + MODULO));
            }
        }
    }
    if (CommonUtil.isNotNull(userId)) {
        User user = userRepository.findById(userId);
        if (CommonUtil.isNotNull(user) && user.getRole().equals(ROLE_CUSTOMER)) {
            Expression<String> exp = root.get(FIELD_CONSTANT_CREDIT_CARD_ID);
            Predicate predicate = exp.in(retrieveCreditCardIdFromUserId(userId));
            predicates.add(predicate);
        }
    }

    query.where(predicates.toArray(new Predicate[] {}));
}

From source file:eu.uqasar.service.AbstractService.java

protected Long performDistinctCountWithEqualPredicate(final Attribute<T, ?> attr, Object value) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Long> query = cb.createQuery(Long.class);
    Root<T> root = query.from(clazz);
    query.where(cb.equal(root.get(attr.getName()), value));
    query.select(cb.countDistinct(root));
    return em.createQuery(query).getSingleResult();
}

From source file:me.ineson.demo.service.utils.RestUtilsTest.java

@SuppressWarnings("unchecked")
@Test//from   ww w .j ava2s  .c om
public void testParseWhereClause() {
    CriteriaBuilder criteriaBuilderMock = mock(CriteriaBuilder.class);
    CriteriaQuery<SolarBody> criteriaQueryMock = mock(CriteriaQuery.class);
    Root<SolarBody> rootMock = mock(Root.class);
    log.debug("mock root {}, builder {}", rootMock, criteriaBuilderMock);

    Join<Object, Object> idFieldPath = mock(Join.class);
    when(rootMock.get("id")).thenReturn(idFieldPath);

    Predicate firstPredicate = mock(Predicate.class);
    when(criteriaBuilderMock.equal(idFieldPath, "22")).thenReturn(firstPredicate);

    Predicate predicate = RestUtils.parseWhereClause("id=22", rootMock, criteriaQueryMock, criteriaBuilderMock,
            null);

    verify(rootMock, times(1)).get("id");
    verifyNoMoreInteractions(rootMock);

    verify(criteriaBuilderMock, times(1)).equal(idFieldPath, "22");
    verifyNoMoreInteractions(criteriaBuilderMock);

    Assert.assertEquals(firstPredicate, predicate);
}

From source file:bq.jpa.demo.query.criteria.service.CriteriaService.java

/**
 * multiple select/*from  w w  w.ja  va 2  s.c o  m*/
 */
public void doSelect2() {
    CriteriaBuilder cb = em.getCriteriaBuilder();

    // method1: tuple
    CriteriaQuery<Tuple> tupleQuery = cb.createTupleQuery();
    Root<Employee> e1 = tupleQuery.from(Employee.class);
    tupleQuery.select(cb.tuple(e1.get("id"), e1.get("name")));
    showResult(tupleQuery);

    // method2: object[] and criteriaquery.multiselec
    CriteriaQuery<Object[]> multiQuery = cb.createQuery(Object[].class);
    Root<Employee> e2 = multiQuery.from(Employee.class);
    multiQuery.multiselect(e2.get("id"), e2.get("name"));
    showResult(multiQuery);
}

From source file:bq.jpa.demo.query.criteria.service.CriteriaService.java

/**
 * in and path://from w w w  . ja v a2 s  .c  o m
 * SELECT e FROM jpa_query_employee e WHERE e.address.state IN ('NY','MI')
 */
@Transactional
public void doWhere3() {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Employee> c = cb.createQuery(Employee.class);
    Root<Employee> e = c.from(Employee.class);
    // method 1 
    c.select(e).where(e.get("address").get("state").in("NY", "MI"));
    showResult(c);

    // method 2
    c.select(e).where(cb.in(e.get("address").get("state")).value("NY").value("MI"));
    showResult(c);
}

From source file:bq.jpa.demo.query.criteria.service.CriteriaService.java

/**
 * NOTE : Hibernate cannot support case in criteria way
 * /*from w  ww  .  j ava 2s. c  o  m*/
 * case 1:
 * SELECT p.name, 
 *          CASE WHEN TYPE(p)=bq.jpa.demo.query.domain.DesignProject  THEN 'dev' 
 *              WHEN TYPE(p)=bq.jpa.demo.query.domain.QualityProject THEN 'QA' 
 *              ELSE 'unknown' 
 *          END 
 * FROM jpa_query_project p
 * 
 * case 2:
 * SELECT p.name, 
 *          CASE TYPE(p)
 *              WHEN bq.jpa.demo.query.domain.DesignProject  THEN 'dev' 
 *              WHEN bq.jpa.demo.query.domain.QualityProject THEN 'QA' 
 *              ELSE 'unknown' 
 *          END 
 * FROM jpa_query_project p
 */
@Transactional
public void doWhere4() {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Object[]> c = cb.createQuery(Object[].class);
    Root<Project> p = c.from(Project.class);

    // method 1
    c.multiselect(p.get("name"), cb.selectCase().when(cb.equal(p.type(), DesignProject.class), "dev")
            .when(cb.equal(p.type(), QualityProject.class), "QA").otherwise("unknown"));

    //      showResult(c);

    // method 2:
    CriteriaQuery<Object[]> c2 = cb.createQuery(Object[].class);
    Root<Project> p2 = c2.from(Project.class);
    c2.multiselect(p2.get("name"), cb.selectCase(p2.type()).when(DesignProject.class, "dev")
            .when(QualityProject.class, "QA").otherwise("unknown"));
    //      showResult(c2);
}

From source file:org.openlmis.fulfillment.repository.custom.impl.OrderRepositoryImpl.java

/**
 * Retrieves the distinct UUIDs of the available requesting facilities.
 *//*w w w .  ja  v a 2  s .  co m*/
@Override
public List<UUID> getRequestingFacilities(List<UUID> supplyingFacilityIds) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<UUID> query = builder.createQuery(UUID.class);
    Root<Order> root = query.from(Order.class);

    if (!isEmpty(supplyingFacilityIds)) {
        Predicate predicate = builder.disjunction();
        for (Object elem : supplyingFacilityIds) {
            predicate = builder.or(predicate, builder.equal(root.get(SUPPLYING_FACILITY_ID), elem));
        }
        query.where(predicate);
    }

    query.select(root.get(REQUESTING_FACILITY_ID)).distinct(true);

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

From source file:net.nan21.dnet.core.business.service.entity.AbstractEntityReadService.java

/**
 * Find an entity of the given type, using as filter criteria the specified
 * list of attribute values. The filter criteria must uniquely identify an
 * entity./*  w  w w .j a v  a 2s  .c  o m*/
 * 
 * @param entityClass
 * @param params
 * @return
 * @throws BusinessException
 */
public <T> T findEntityByAttributes(Class<T> entityClass, Map<String, Object> params) {
    CriteriaBuilder cb = this.getEntityManager().getCriteriaBuilder();
    CriteriaQuery<T> cq = cb.createQuery(entityClass);
    Root<T> root = cq.from(entityClass);
    cq.select(root);
    Assert.notNull(params);
    Predicate p = null;
    if (entityClass.isAssignableFrom(IModelWithClientId.class)) {
        p = cb.equal(root.get("clientId"), Session.user.get().getClient().getId());
    }
    for (Map.Entry<String, Object> entry : params.entrySet()) {
        p = cb.and(cb.equal(root.get(entry.getKey()), entry.getValue()));
    }
    cq.where(p);
    TypedQuery<T> query = this.getEntityManager().createQuery(cq);
    return (T) query.getSingleResult();
}