Example usage for javax.persistence.criteria CriteriaBuilder equal

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

Introduction

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

Prototype

Predicate equal(Expression<?> x, Object y);

Source Link

Document

Create a predicate for testing the arguments for equality.

Usage

From source file:com.zero.dao.impl.BaseDaoImpl.java

private void addRestrictions(CriteriaQuery<T> criteriaQuery, List<Filter> filters) {
    if (criteriaQuery == null || filters == null || filters.isEmpty()) {
        return;/*  w ww  . jav  a 2  s. co m*/
    }
    Root<T> root = getRoot(criteriaQuery);
    if (root == null) {
        return;
    }
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    Predicate restrictions = criteriaQuery.getRestriction() != null ? criteriaQuery.getRestriction()
            : criteriaBuilder.conjunction();
    for (Filter filter : filters) {
        if (filter == null || StringUtils.isEmpty(filter.getProperty())) {
            continue;
        }
        if (filter.getOperator() == Operator.eq && filter.getValue() != null) {
            if (filter.getIgnoreCase() != null && filter.getIgnoreCase()
                    && filter.getValue() instanceof String) {
                restrictions = criteriaBuilder.and(restrictions,
                        criteriaBuilder.equal(criteriaBuilder.lower(root.<String>get(filter.getProperty())),
                                ((String) filter.getValue()).toLowerCase()));
            } else {
                restrictions = criteriaBuilder.and(restrictions,
                        criteriaBuilder.equal(root.get(filter.getProperty()), filter.getValue()));
            }
        } else if (filter.getOperator() == Operator.ne && filter.getValue() != null) {
            if (filter.getIgnoreCase() != null && filter.getIgnoreCase()
                    && filter.getValue() instanceof String) {
                restrictions = criteriaBuilder.and(restrictions,
                        criteriaBuilder.notEqual(criteriaBuilder.lower(root.<String>get(filter.getProperty())),
                                ((String) filter.getValue()).toLowerCase()));
            } else {
                restrictions = criteriaBuilder.and(restrictions,
                        criteriaBuilder.notEqual(root.get(filter.getProperty()), filter.getValue()));
            }
        } else if (filter.getOperator() == Operator.gt && filter.getValue() != null) {
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.gt(root.<Number>get(filter.getProperty()), (Number) filter.getValue()));
        } else if (filter.getOperator() == Operator.lt && filter.getValue() != null) {
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.lt(root.<Number>get(filter.getProperty()), (Number) filter.getValue()));
        } else if (filter.getOperator() == Operator.ge && filter.getValue() != null) {
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.ge(root.<Number>get(filter.getProperty()), (Number) filter.getValue()));
        } else if (filter.getOperator() == Operator.le && filter.getValue() != null) {
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.le(root.<Number>get(filter.getProperty()), (Number) filter.getValue()));
        } else if (filter.getOperator() == Operator.like && filter.getValue() != null
                && filter.getValue() instanceof String) {
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.like(root.<String>get(filter.getProperty()), (String) filter.getValue()));
        } else if (filter.getOperator() == Operator.in && filter.getValue() != null) {
            restrictions = criteriaBuilder.and(restrictions,
                    root.get(filter.getProperty()).in(filter.getValue()));
        } else if (filter.getOperator() == Operator.isNull) {
            restrictions = criteriaBuilder.and(restrictions, root.get(filter.getProperty()).isNull());
        } else if (filter.getOperator() == Operator.isNotNull) {
            restrictions = criteriaBuilder.and(restrictions, root.get(filter.getProperty()).isNotNull());
        }
    }
    criteriaQuery.where(restrictions);
}

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

@SuppressWarnings("unchecked")
@Test/*w w w. j a v a 2s .c o  m*/
public void testParseWhereClauseMultipleWithTransation() {
    CriteriaBuilder criteriaBuilderMock = mock(CriteriaBuilder.class);
    CriteriaQuery<SolarBody> criteriaQueryMock = mock(CriteriaQuery.class);
    Root<SolarBody> rootMock = mock(Root.class);
    log.info("mock root {}, builder {}", rootMock, criteriaBuilderMock);

    Map<String, String> translations = new HashMap<String, String>();
    translations.put("cmrId", "cmr.id");

    Join<Object, Object> nameFieldPath = mock(Join.class, "name field");
    when(rootMock.get("name")).thenReturn(nameFieldPath);

    Join<Object, Object> cmrRecordPath = mock(Join.class, "cmr field");
    when(rootMock.join("cmr")).thenReturn(cmrRecordPath);

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

    Predicate firstPredicate = mock(Predicate.class, "1st prediccate");
    when(criteriaBuilderMock.equal(nameFieldPath, "test")).thenReturn(firstPredicate);

    Predicate secondPredicate = mock(Predicate.class, "2nd prediccate");
    when(criteriaBuilderMock.equal(idFieldPath, "22")).thenReturn(secondPredicate);

    Predicate andedPredicates[] = { firstPredicate, secondPredicate };
    Predicate finalPredicate = mock(Predicate.class, "final prediccate");
    when(criteriaBuilderMock.and(andedPredicates)).thenReturn(finalPredicate);

    Predicate predicate = RestUtils.parseWhereClause("name=test,cmrId=22", rootMock, criteriaQueryMock,
            criteriaBuilderMock, translations);

    verify(rootMock, times(1)).get("name");
    verify(rootMock, times(1)).join("cmr");
    verifyNoMoreInteractions(rootMock);

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

    verify(criteriaBuilderMock, times(1)).equal(nameFieldPath, "test");
    verify(criteriaBuilderMock, times(1)).equal(idFieldPath, "22");
    verify(criteriaBuilderMock, times(1)).and(andedPredicates);
    verifyNoMoreInteractions(criteriaBuilderMock);

    Assert.assertEquals(finalPredicate, predicate);
}

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

public List<Product> findList(ProductCategory productCategory, Brand brand, Promotion promotion, List<Tag> tags,
        Map<Attribute, String> attributeValue, BigDecimal startPrice, BigDecimal endPrice, Boolean isMarketable,
        Boolean isList, Boolean isTop, Boolean isGift, Boolean isOutOfStock, Boolean isStockAlert,
        OrderType orderType, Integer count, List<Filter> filters, List<Order> orders) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Product> criteriaQuery = criteriaBuilder.createQuery(Product.class);
    Root<Product> root = criteriaQuery.from(Product.class);
    criteriaQuery.select(root);//www  . java2 s .  co  m
    Predicate restrictions = criteriaBuilder.conjunction();
    if (productCategory != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.or(criteriaBuilder.equal(root.get("productCategory"), productCategory),
                        criteriaBuilder.like(root.get("productCategory").<String>get("treePath"),
                                "%" + ProductCategory.TREE_PATH_SEPARATOR + productCategory.getId()
                                        + ProductCategory.TREE_PATH_SEPARATOR + "%")));
    }
    if (brand != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("brand"), brand));
    }
    if (promotion != null) {
        Subquery<Product> subquery1 = criteriaQuery.subquery(Product.class);
        Root<Product> subqueryRoot1 = subquery1.from(Product.class);
        subquery1.select(subqueryRoot1);
        subquery1.where(criteriaBuilder.equal(subqueryRoot1, root),
                criteriaBuilder.equal(subqueryRoot1.join("promotions"), promotion));

        Subquery<Product> subquery2 = criteriaQuery.subquery(Product.class);
        Root<Product> subqueryRoot2 = subquery2.from(Product.class);
        subquery2.select(subqueryRoot2);
        subquery2.where(criteriaBuilder.equal(subqueryRoot2, root),
                criteriaBuilder.equal(subqueryRoot2.join("productCategory").join("promotions"), promotion));

        Subquery<Product> subquery3 = criteriaQuery.subquery(Product.class);
        Root<Product> subqueryRoot3 = subquery3.from(Product.class);
        subquery3.select(subqueryRoot3);
        subquery3.where(criteriaBuilder.equal(subqueryRoot3, root),
                criteriaBuilder.equal(subqueryRoot3.join("brand").join("promotions"), promotion));

        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.exists(subquery1),
                criteriaBuilder.exists(subquery2), criteriaBuilder.exists(subquery3)));
    }
    if (tags != null && !tags.isEmpty()) {
        Subquery<Product> subquery = criteriaQuery.subquery(Product.class);
        Root<Product> subqueryRoot = subquery.from(Product.class);
        subquery.select(subqueryRoot);
        subquery.where(criteriaBuilder.equal(subqueryRoot, root), subqueryRoot.join("tags").in(tags));
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.exists(subquery));
    }
    if (attributeValue != null) {
        for (Entry<Attribute, String> entry : attributeValue.entrySet()) {
            String propertyName = Product.ATTRIBUTE_VALUE_PROPERTY_NAME_PREFIX
                    + entry.getKey().getPropertyIndex();
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.equal(root.get(propertyName), entry.getValue()));
        }
    }
    if (startPrice != null && endPrice != null && startPrice.compareTo(endPrice) > 0) {
        BigDecimal temp = startPrice;
        startPrice = endPrice;
        endPrice = temp;
    }
    if (startPrice != null && startPrice.compareTo(new BigDecimal(0)) >= 0) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.ge(root.<Number>get("price"), startPrice));
    }
    if (endPrice != null && endPrice.compareTo(new BigDecimal(0)) >= 0) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.le(root.<Number>get("price"), endPrice));
    }
    if (isMarketable != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isMarketable"), isMarketable));
    }
    if (isList != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isList"), isList));
    }
    if (isTop != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isTop"), isTop));
    }
    if (isGift != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isGift"), isGift));
    }
    Path<Integer> stock = root.get("stock");
    Path<Integer> allocatedStock = root.get("allocatedStock");
    if (isOutOfStock != null) {
        if (isOutOfStock) {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNotNull(stock),
                    criteriaBuilder.lessThanOrEqualTo(stock, allocatedStock));
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.isNull(stock),
                    criteriaBuilder.greaterThan(stock, allocatedStock)));
        }
    }
    if (isStockAlert != null) {
        Setting setting = SettingUtils.get();
        if (isStockAlert) {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNotNull(stock),
                    criteriaBuilder.lessThanOrEqualTo(stock,
                            criteriaBuilder.sum(allocatedStock, setting.getStockAlertCount())));
        } else {
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.or(criteriaBuilder.isNull(stock), criteriaBuilder.greaterThan(stock,
                            criteriaBuilder.sum(allocatedStock, setting.getStockAlertCount()))));
        }
    }
    criteriaQuery.where(restrictions);
    if (orderType == OrderType.priceAsc) {
        orders.add(Order.asc("price"));
        orders.add(Order.desc("createDate"));
    } else if (orderType == OrderType.priceDesc) {
        orders.add(Order.desc("price"));
        orders.add(Order.desc("createDate"));
    } else if (orderType == OrderType.salesDesc) {
        orders.add(Order.desc("sales"));
        orders.add(Order.desc("createDate"));
    } else if (orderType == OrderType.scoreDesc) {
        orders.add(Order.desc("score"));
        orders.add(Order.desc("createDate"));
    } else if (orderType == OrderType.dateDesc) {
        orders.add(Order.desc("createDate"));
    } else {
        orders.add(Order.desc("isTop"));
        orders.add(Order.desc("modifyDate"));
    }
    return super.findList(criteriaQuery, null, count, filters, orders);
}

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

public Page<Product> findPage(ProductCategory productCategory, Brand brand, Promotion promotion, List<Tag> tags,
        Map<Attribute, String> attributeValue, BigDecimal startPrice, BigDecimal endPrice, Boolean isMarketable,
        Boolean isList, Boolean isTop, Boolean isGift, Boolean isOutOfStock, Boolean isStockAlert,
        OrderType orderType, Pageable pageable) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Product> criteriaQuery = criteriaBuilder.createQuery(Product.class);
    Root<Product> root = criteriaQuery.from(Product.class);
    criteriaQuery.select(root);//  w  w  w  .j  a  va  2  s . c om
    Predicate restrictions = criteriaBuilder.conjunction();
    if (productCategory != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.or(criteriaBuilder.equal(root.get("productCategory"), productCategory),
                        criteriaBuilder.like(root.get("productCategory").<String>get("treePath"),
                                "%" + ProductCategory.TREE_PATH_SEPARATOR + productCategory.getId()
                                        + ProductCategory.TREE_PATH_SEPARATOR + "%")));
    }
    if (brand != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("brand"), brand));
    }
    if (promotion != null) {
        Subquery<Product> subquery1 = criteriaQuery.subquery(Product.class);
        Root<Product> subqueryRoot1 = subquery1.from(Product.class);
        subquery1.select(subqueryRoot1);
        subquery1.where(criteriaBuilder.equal(subqueryRoot1, root),
                criteriaBuilder.equal(subqueryRoot1.join("promotions"), promotion));

        Subquery<Product> subquery2 = criteriaQuery.subquery(Product.class);
        Root<Product> subqueryRoot2 = subquery2.from(Product.class);
        subquery2.select(subqueryRoot2);
        subquery2.where(criteriaBuilder.equal(subqueryRoot2, root),
                criteriaBuilder.equal(subqueryRoot2.join("productCategory").join("promotions"), promotion));

        Subquery<Product> subquery3 = criteriaQuery.subquery(Product.class);
        Root<Product> subqueryRoot3 = subquery3.from(Product.class);
        subquery3.select(subqueryRoot3);
        subquery3.where(criteriaBuilder.equal(subqueryRoot3, root),
                criteriaBuilder.equal(subqueryRoot3.join("brand").join("promotions"), promotion));

        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.exists(subquery1),
                criteriaBuilder.exists(subquery2), criteriaBuilder.exists(subquery3)));
    }
    if (tags != null && !tags.isEmpty()) {
        Subquery<Product> subquery = criteriaQuery.subquery(Product.class);
        Root<Product> subqueryRoot = subquery.from(Product.class);
        subquery.select(subqueryRoot);
        subquery.where(criteriaBuilder.equal(subqueryRoot, root), subqueryRoot.join("tags").in(tags));
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.exists(subquery));
    }
    if (attributeValue != null) {
        for (Entry<Attribute, String> entry : attributeValue.entrySet()) {
            String propertyName = Product.ATTRIBUTE_VALUE_PROPERTY_NAME_PREFIX
                    + entry.getKey().getPropertyIndex();
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.equal(root.get(propertyName), entry.getValue()));
        }
    }
    if (startPrice != null && endPrice != null && startPrice.compareTo(endPrice) > 0) {
        BigDecimal temp = startPrice;
        startPrice = endPrice;
        endPrice = temp;
    }
    if (startPrice != null && startPrice.compareTo(new BigDecimal(0)) >= 0) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.ge(root.<Number>get("price"), startPrice));
    }
    if (endPrice != null && endPrice.compareTo(new BigDecimal(0)) >= 0) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.le(root.<Number>get("price"), endPrice));
    }
    if (isMarketable != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isMarketable"), isMarketable));
    }
    if (isList != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isList"), isList));
    }
    if (isTop != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isTop"), isTop));
    }
    if (isGift != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isGift"), isGift));
    }
    Path<Integer> stock = root.get("stock");
    Path<Integer> allocatedStock = root.get("allocatedStock");
    if (isOutOfStock != null) {
        if (isOutOfStock) {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNotNull(stock),
                    criteriaBuilder.lessThanOrEqualTo(stock, allocatedStock));
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.isNull(stock),
                    criteriaBuilder.greaterThan(stock, allocatedStock)));
        }
    }
    if (isStockAlert != null) {
        Setting setting = SettingUtils.get();
        if (isStockAlert) {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNotNull(stock),
                    criteriaBuilder.lessThanOrEqualTo(stock,
                            criteriaBuilder.sum(allocatedStock, setting.getStockAlertCount())));
        } else {
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.or(criteriaBuilder.isNull(stock), criteriaBuilder.greaterThan(stock,
                            criteriaBuilder.sum(allocatedStock, setting.getStockAlertCount()))));
        }
    }
    criteriaQuery.where(restrictions);
    List<Order> orders = pageable.getOrders();
    if (orderType == OrderType.priceAsc) {
        orders.add(Order.asc("price"));
        orders.add(Order.desc("createDate"));
    } else if (orderType == OrderType.priceDesc) {
        orders.add(Order.desc("price"));
        orders.add(Order.desc("createDate"));
    } else if (orderType == OrderType.salesDesc) {
        orders.add(Order.desc("sales"));
        orders.add(Order.desc("createDate"));
    } else if (orderType == OrderType.scoreDesc) {
        orders.add(Order.desc("score"));
        orders.add(Order.desc("createDate"));
    } else if (orderType == OrderType.dateDesc) {
        orders.add(Order.desc("createDate"));
    } else {
        orders.add(Order.desc("isTop"));
        orders.add(Order.desc("modifyDate"));
    }
    return super.findPage(criteriaQuery, pageable);
}

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

public List<Object[]> findPurchaseList(Date beginDate, Date endDate, Integer count) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Object[]> criteriaQuery = criteriaBuilder.createQuery(Object[].class);
    Root<Member> member = criteriaQuery.from(Member.class);
    Join<Product, Order> orders = member.join("orders");
    criteriaQuery.multiselect(member.get("id"), member.get("username"), member.get("email"),
            member.get("point"), member.get("amount"), member.get("balance"),
            criteriaBuilder.sum(orders.<BigDecimal>get("amountPaid")));
    Predicate restrictions = criteriaBuilder.conjunction();
    if (beginDate != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.greaterThanOrEqualTo(orders.<Date>get("createDate"), beginDate));
    }//from  ww  w.  j a va 2  s  .  c o  m
    if (endDate != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.lessThanOrEqualTo(orders.<Date>get("createDate"), endDate));
    }
    restrictions = criteriaBuilder.and(restrictions,
            criteriaBuilder.equal(orders.get("orderStatus"), OrderStatus.completed),
            criteriaBuilder.equal(orders.get("paymentStatus"), PaymentStatus.paid));
    criteriaQuery.where(restrictions);
    criteriaQuery.groupBy(member.get("id"), member.get("username"), member.get("email"), member.get("point"),
            member.get("amount"), member.get("balance"));
    criteriaQuery.orderBy(criteriaBuilder.desc(criteriaBuilder.sum(orders.<BigDecimal>get("amountPaid"))));
    TypedQuery<Object[]> query = entityManager.createQuery(criteriaQuery).setFlushMode(FlushModeType.COMMIT);
    if (count != null && count >= 0) {
        query.setMaxResults(count);
    }
    return query.getResultList();
}

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

/**
 * count entity by ParamInfo/* w  ww .j  a  v  a2 s .com*/
 *
 * @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:com.evolveum.midpoint.repo.sql.helpers.ObjectRetriever.java

public <T extends ObjectType> PrismObject<T> getObjectInternal(Session session, Class<T> type, String oid,
        Collection<SelectorOptions<GetOperationOptions>> options, boolean lockForUpdate,
        OperationResult operationResult)
        throws ObjectNotFoundException, SchemaException, DtoTranslationException {

    boolean lockedForUpdateViaHibernate = false;
    boolean lockedForUpdateViaSql = false;

    LockOptions lockOptions = new LockOptions();
    //todo fix lock for update!!!!!
    if (lockForUpdate) {
        if (getConfiguration().isLockForUpdateViaHibernate()) {
            lockOptions.setLockMode(LockMode.PESSIMISTIC_WRITE);
            lockedForUpdateViaHibernate = true;
        } else if (getConfiguration().isLockForUpdateViaSql()) {
            LOGGER.trace("Trying to lock object {} for update (via SQL)", oid);
            long time = System.currentTimeMillis();
            NativeQuery q = session.createNativeQuery("select oid from m_object where oid = ? for update");
            q.setParameter(1, oid);//  w w w . j a va 2 s .  c  om
            Object result = q.uniqueResult();
            if (result == null) {
                return throwObjectNotFoundException(type, oid);
            }
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("Locked via SQL (in {} ms)", System.currentTimeMillis() - time);
            }
            lockedForUpdateViaSql = true;
        }
    }

    if (LOGGER.isTraceEnabled()) {
        if (lockedForUpdateViaHibernate) {
            LOGGER.trace("Getting object {} with locking for update (via hibernate)", oid);
        } else if (lockedForUpdateViaSql) {
            LOGGER.trace("Getting object {}, already locked for update (via SQL)", oid);
        } else {
            LOGGER.trace("Getting object {} without locking for update", oid);
        }
    }

    GetObjectResult fullObject = null;
    if (!lockForUpdate) {
        Query query = session.getNamedQuery("get.object");
        query.setParameter("oid", oid);
        query.setResultTransformer(GetObjectResult.RESULT_STYLE.getResultTransformer());
        query.setLockOptions(lockOptions);

        fullObject = (GetObjectResult) query.uniqueResult();
    } else {
        // we're doing update after this get, therefore we load full object right now
        // (it would be loaded during merge anyway)
        // this just loads object to hibernate session, probably will be removed later. Merge after this get
        // will be faster. Read and use object only from fullObject column.
        // todo remove this later [lazyman]
        Class clazz = ClassMapper.getHQLTypeClass(type);

        CriteriaBuilder cb = session.getCriteriaBuilder();
        CriteriaQuery cq = cb.createQuery(clazz);
        cq.where(cb.equal(cq.from(clazz).get("oid"), oid));

        Query query = session.createQuery(cq);
        query.setLockOptions(lockOptions);

        RObject obj = (RObject) query.uniqueResult();

        if (obj != null) {
            fullObject = new GetObjectResult(obj.getOid(), obj.getFullObject(), obj.getStringsCount(),
                    obj.getLongsCount(), obj.getDatesCount(), obj.getReferencesCount(), obj.getPolysCount(),
                    obj.getBooleansCount());
        }
    }

    LOGGER.trace("Got it.");
    if (fullObject == null) {
        throwObjectNotFoundException(type, oid);
    }

    LOGGER.trace("Transforming data to JAXB type.");
    PrismObject<T> prismObject = updateLoadedObject(fullObject, type, oid, options, null, session,
            operationResult);
    validateObjectType(prismObject, type);

    // this was implemented to allow report parsing errors as warnings to upper layers;
    // however, it causes problems when serialization problems are encountered: in such cases, we put
    // FATAL_ERROR to the result here, and it should be then removed or muted (which is a complication)
    // -- so, as the parsing errors are not implemented, we disabled this code as well

    //         subResult.computeStatusIfUnknown();
    //         if (subResult.isWarning() || subResult.isError() || subResult.isInProgress()) {
    //            prismObject.asObjectable().setFetchResult(subResult.createOperationResultType());
    //         }

    return prismObject;
}

From source file:org.apereo.lap.dao.RiskConfidenceRepositoryImpl.java

public List<RiskConfidence> findByUserCourseDate(final String user, final String course) {

    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<RiskConfidence> criteria = builder.createQuery(RiskConfidence.class);
    Root<RiskConfidence> root = criteria.from(RiskConfidence.class);
    EntityType<RiskConfidence> type = entityManager.getMetamodel().entity(RiskConfidence.class);
    criteria.orderBy(builder.desc(root.get("dateCreated")));

    List<RiskConfidence> lastRiskConfidences = entityManager.createQuery(criteria).setFirstResult(0)
            .setMaxResults(1).getResultList();

    if (lastRiskConfidences == null || lastRiskConfidences.isEmpty()) {
        logger.warn("No risk confidence records found");
        return new ArrayList<RiskConfidence>();
    }//from   www .j av  a 2s.co  m

    RiskConfidence lastRickConfidence = lastRiskConfidences.get(0);

    builder = entityManager.getCriteriaBuilder();
    criteria = builder.createQuery(RiskConfidence.class);
    root = criteria.from(RiskConfidence.class);
    type = entityManager.getMetamodel().entity(RiskConfidence.class);

    Predicate groupPredicate = builder.equal(root.get("groupId"), lastRickConfidence.getGroupId());

    if (!StringUtils.isEmpty(user) && !StringUtils.isEmpty(course)) {
        criteria.where(groupPredicate,
                builder.equal(
                        builder.lower(
                                root.get(type.getDeclaredSingularAttribute("alternativeId", String.class))),
                        user.toLowerCase()),
                builder.equal(
                        builder.lower(root.get(type.getDeclaredSingularAttribute("courseId", String.class))),
                        course.toLowerCase()));
    } else if (!StringUtils.isEmpty(user)) {
        criteria.where(groupPredicate,
                builder.equal(
                        builder.lower(
                                root.get(type.getDeclaredSingularAttribute("alternativeId", String.class))),
                        user.toLowerCase()));
    } else if (!StringUtils.isEmpty(course)) {
        criteria.where(groupPredicate,
                builder.equal(
                        builder.lower(root.get(type.getDeclaredSingularAttribute("courseId", String.class))),
                        course.toLowerCase()));
    } else {
        criteria.where(groupPredicate);
    }

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

From source file:org.businessmanager.dao.GenericDaoImpl.java

@SuppressWarnings("unchecked")
private List<Predicate> createFilterList(Map<SingularAttribute<T, ?>, Object> filterAttributes,
        boolean enableLikeSearch, CriteriaBuilder queryBuilder, Root<T> rootQuery) {
    List<Predicate> predicateList = new ArrayList<Predicate>();
    if (filterAttributes != null) {
        Iterator<SingularAttribute<T, ?>> iter = filterAttributes.keySet().iterator();
        while (iter.hasNext()) {
            SingularAttribute<T, ?> key = iter.next();
            Object value = filterAttributes.get(key);
            if (enableLikeSearch) {
                String searchKey = value.toString();
                if (!value.toString().contains("%")) {
                    searchKey = "%" + value.toString() + "%";
                }//from   w  w  w. j  av  a2s.  c o m

                Expression<String> lowerKey = queryBuilder.lower((Expression<String>) rootQuery.get(key));
                Predicate predicate = queryBuilder.like(lowerKey, searchKey.toLowerCase());
                predicateList.add(predicate);
            } else {
                Predicate predicate = queryBuilder.equal(rootQuery.get(key), value);
                predicateList.add(predicate);
            }
        }
    }
    return predicateList;
}

From source file:com.globalhackv.app.repository.CitationSpec.java

@Override
public Predicate toPredicate(Root<Citation> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
    List<Predicate> predicates = new ArrayList<Predicate>();

    if (StringUtils.isNotBlank(example.getLastName())) {
        predicates.add(/*from www .  j  a v  a2 s  . com*/
                cb.like(cb.lower(root.get(Citation_.lastName)), example.getLastName().toLowerCase() + "%"));
    }

    if (StringUtils.isNotBlank(example.getFirstName())) {
        predicates.add(
                cb.like(cb.lower(root.get(Citation_.firstName)), example.getFirstName().toLowerCase() + "%"));
    }

    if (StringUtils.isNotBlank(example.getDateOfBirth())) {
        predicates.add(cb.like(cb.lower(root.get(Citation_.dateOfBirth)),
                example.getDateOfBirth().toLowerCase() + "%"));
    }

    if (StringUtils.isNotBlank(example.getDriversLicense())) {
        predicates.add(cb.like(cb.lower(root.get(Citation_.driversLicense)),
                example.getDriversLicense().toLowerCase() + "%"));
    }

    if (StringUtils.isNotBlank(example.getAddress())) {
        predicates
                .add(cb.like(cb.lower(root.get(Citation_.address)), example.getAddress().toLowerCase() + "%"));
    }
    if (example.getCitationNumber() != 0) {
        predicates.add(cb.equal(root.get(Citation_.citationNumber), example.getCitationNumber()));
    }

    return andTogether(predicates, cb);
}