Example usage for javax.persistence.criteria CriteriaBuilder and

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

Introduction

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

Prototype

Predicate and(Expression<Boolean> x, Expression<Boolean> y);

Source Link

Document

Create a conjunction of the given boolean expressions.

Usage

From source file:net.groupbuy.dao.impl.OrderDaoImpl.java

public BigDecimal getSalesAmount(Date beginDate, Date endDate) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<BigDecimal> criteriaQuery = criteriaBuilder.createQuery(BigDecimal.class);
    Root<Order> root = criteriaQuery.from(Order.class);
    criteriaQuery.select(criteriaBuilder.sum(root.<BigDecimal>get("amountPaid")));
    Predicate restrictions = criteriaBuilder.conjunction();
    restrictions = criteriaBuilder.and(restrictions,
            criteriaBuilder.equal(root.get("orderStatus"), OrderStatus.completed));
    if (beginDate != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.greaterThanOrEqualTo(root.<Date>get("createDate"), beginDate));
    }/*ww w  .  j a va  2 s  .c om*/
    if (endDate != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.lessThanOrEqualTo(root.<Date>get("createDate"), endDate));
    }
    criteriaQuery.where(restrictions);
    return entityManager.createQuery(criteriaQuery).setFlushMode(FlushModeType.COMMIT).getSingleResult();
}

From source file:net.groupbuy.dao.impl.OrderDaoImpl.java

public Integer getSalesVolume(Date beginDate, Date endDate) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Integer> criteriaQuery = criteriaBuilder.createQuery(Integer.class);
    Root<Order> root = criteriaQuery.from(Order.class);
    criteriaQuery.select(criteriaBuilder.sum(root.join("orderItems").<Integer>get("shippedQuantity")));
    Predicate restrictions = criteriaBuilder.conjunction();
    restrictions = criteriaBuilder.and(restrictions,
            criteriaBuilder.equal(root.get("orderStatus"), OrderStatus.completed));
    if (beginDate != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.greaterThanOrEqualTo(root.<Date>get("createDate"), beginDate));
    }//from w w w  . j  av a 2  s. c o m
    if (endDate != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.lessThanOrEqualTo(root.<Date>get("createDate"), endDate));
    }
    criteriaQuery.where(restrictions);
    return entityManager.createQuery(criteriaQuery).setFlushMode(FlushModeType.COMMIT).getSingleResult();
}

From source file:edu.umm.radonc.ca_dash.model.ActivityFacade.java

public int itemsDateRangeCount(Date start, Date end) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery cq = cb.createQuery(ActivityAIPC.class);
    Root<ActivityAIPC> rt = cq.from(ActivityAIPC.class);
    cq.select(cb.count(rt.get(ActivityAIPC_.actinstproccodeser)));
    cq.where(cb.and(rt.get(ActivityAIPC_.fromdateofservice).isNotNull(),
            cb.and(cb.notEqual(rt.get(ActivityAIPC_.procedurecodeser), 528),
                    cb.notEqual(rt.get(ActivityAIPC_.procedurecodeser), 529),
                    cb.notEqual(rt.get(ActivityAIPC_.procedurecodeser), 530),
                    cb.between(rt.get(ActivityAIPC_.fromdateofservice), start, end))));

    Query q = em.createQuery(cq);
    return ((Long) (q.getSingleResult())).intValue();

}

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

/**
 * {@inheritDoc}//from  ww w .  jav a 2  s.c  o m
 */
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.home.ln_spring.ch10.service.jpa.ContactServiceImplOld.java

@Override
@Transactional(readOnly = true)//from  w w  w . ja va 2 s. co m
public List<Contact> findByCriteriaQuery(String firstName, String lastName) {
    log.info("Finding contact for firstName: " + firstName + " and lastName: " + lastName);

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Contact> criteriaQuery = cb.createQuery(Contact.class);
    Root<Contact> contactRoot = criteriaQuery.from(Contact.class);
    contactRoot.fetch(Contact_.contactTelDetails, JoinType.LEFT);
    contactRoot.fetch(Contact_.hobbies, JoinType.LEFT);

    criteriaQuery.select(contactRoot).distinct(true);

    Predicate criteria = cb.conjunction();
    if (firstName != null) {
        Predicate p = cb.equal(contactRoot.get(Contact_.firstName), firstName);
        criteria = cb.and(criteria, p);
    }

    if (lastName != null) {
        Predicate p = cb.equal(contactRoot.get(Contact_.lastName), lastName);
        criteria = cb.and(criteria, p);
    }

    criteriaQuery.where(criteria);
    List<Contact> result = em.createQuery(criteriaQuery).getResultList();
    return result;
}

From source file:com.vladmihalcea.HibernateCriteriaTest.java

private Product getProduct_Mercifully() {
    return transactionTemplate.execute(new TransactionCallback<Product>() {
        @Override//from  ww w  .  j  a va  2  s  .  co m
        public Product doInTransaction(TransactionStatus transactionStatus) {
            CriteriaBuilder cb = entityManager.getCriteriaBuilder();
            CriteriaQuery<Product> query = cb.createQuery(Product.class);
            Root<Product> productRoot = query.from(Product.class);
            Join<Product, WarehouseProductInfo> warehouseProductInfoJoin = productRoot
                    .join(Product_.warehouseProductInfo);

            query.select(productRoot).where(cb.and(cb.equal(productRoot.get(Product_.code), "tvCode"),
                    cb.gt(warehouseProductInfoJoin.get(WarehouseProductInfo_.quantity), 50)));
            return entityManager.createQuery(query).getSingleResult();
        }
    });
}

From source file:com.order.erp.web.controller.SystemController.java

@RequestMapping(path = "amoeba", method = RequestMethod.GET)
public String amoebaIndex(HttpServletRequest request,
        @RequestParam(name = "keyword", required = false) String keyword,
        @PageableDefault(page = 0, size = 10, sort = "id", direction = Direction.ASC) Pageable pageable,
        ModelMap model) {// w w w  .  jav a 2 s.c  o m
    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    User me = staffService.findByAccountUsername(((UserDetails) principal).getUsername());
    Company company = me.getCompany();

    final String finalKeyword = keyword;
    final Company finalCompany = company;
    Page<Amoeba> page = adminService.findAmoebas(new Specification<Amoeba>() {
        public Predicate toPredicate(Root<Amoeba> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            query.distinct(true);
            Predicate p1 = cb.equal(root.get("company").as(Company.class), finalCompany);
            Predicate p2 = cb.conjunction();
            if (StringUtils.isNotBlank(finalKeyword)) {
                p2 = cb.like(root.get("name").as(String.class), "%" + finalKeyword + "%");
            }
            Predicate p_result = cb.and(p1, p2);
            return p_result;
        }
    }, pageable);

    model.put("user", me);
    model.put("company", company);
    model.put("page", page);
    String json = JSON.toJSONString(page, SerializerFeature.PrettyFormat);
    System.out.println(json);
    return "/system/amoeba_list";
}

From source file:com.alliander.osgp.adapter.ws.infra.specifications.JpaDeviceSpecifications.java

@Override
public Specification<Device> forOwner(final String organisation) throws ArgumentNullOrEmptyException {
    if (organisation == null) {
        throw new ArgumentNullOrEmptyException("owner");
    }/* ww w.j a v a 2  s  .  c om*/

    return new Specification<Device>() {
        @Override
        public Predicate toPredicate(final Root<Device> deviceRoot, final CriteriaQuery<?> query,
                final CriteriaBuilder cb) {

            final Subquery<Long> subquery = query.subquery(Long.class);
            final Root<DeviceAuthorization> deviceAuthorizationRoot = subquery.from(DeviceAuthorization.class);
            subquery.select(deviceAuthorizationRoot.get("device").get("id").as(Long.class));
            subquery.where(cb.and(
                    cb.like(cb.upper(deviceAuthorizationRoot.get("organisation").<String>get("name")),
                            organisation.toUpperCase()),
                    cb.equal(deviceAuthorizationRoot.get("functionGroup"),
                            DeviceFunctionGroup.OWNER.ordinal())));
            return cb.in(deviceRoot.get("id")).value(subquery);
        }
    };
}

From source file:ch.puzzle.itc.mobiliar.business.resourcegroup.control.ResourceGroupRepository.java

/**
 *
 * @param name//from  w w  w  .  jav a  2s.  c  o  m
 * @param resourceTypeId
 * @return
 */
public ResourceGroupEntity loadUniqueGroupByNameAndType(String name, Integer resourceTypeId) {
    ResourceGroupEntity result = null;
    try {
        CriteriaBuilder cb = entityManager.getCriteriaBuilder();
        CriteriaQuery<ResourceGroupEntity> q = cb.createQuery(ResourceGroupEntity.class);
        Root<ResourceGroupEntity> r = q.from(ResourceGroupEntity.class);
        r.fetch("resources");
        Join<ResourceGroupEntity, ResourceEntity> resources = r.join("resources");
        Predicate typePred = cb.equal(resources.get("resourceType").get("id"), resourceTypeId);
        Predicate resNamePred = cb.equal(resources.get("name"), name);

        q.where(cb.and(typePred, resNamePred));

        q.distinct(true);

        result = entityManager.createQuery(q).getSingleResult();
    } catch (NoResultException e) {
        // do nothing
    }
    return result;
}

From source file:se.kth.csc.persist.JPAStore.java

@Override
public QueuePosition fetchQueuePositionWithQueueAndUser(String queueName, String userName) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<QueuePosition> q = cb.createQuery(QueuePosition.class);

    Root<QueuePosition> queuePosition = q.from(QueuePosition.class);
    Join<QueuePosition, Queue> queue = queuePosition.join(QueuePosition_.queue);
    Join<QueuePosition, Account> account = queuePosition.join(QueuePosition_.account);

    try {/*from  w  w w .j a v  a2  s.  c  om*/
        return entityManager
                .createQuery(
                        q.select(queuePosition)
                                .where(cb.and(cb.equal(queue.get(Queue_.name), queueName),
                                        cb.equal(account.get(Account_.principalName), userName))))
                .getSingleResult();
    } catch (NoResultException e) {
        return null;
    }
}