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:ca.uhn.fhir.jpa.dao.SearchBuilder.java

private Predicate createPredicateToken(IQueryParameterType theParameter, String theParamName,
        CriteriaBuilder theBuilder,
        From<ResourceIndexedSearchParamToken, ResourceIndexedSearchParamToken> theFrom) {
    String code;/*  w w  w  .  j a  v  a  2  s . co  m*/
    String system;
    TokenParamModifier modifier = null;
    if (theParameter instanceof TokenParam) {
        TokenParam id = (TokenParam) theParameter;
        system = id.getSystem();
        code = (id.getValue());
        modifier = id.getModifier();
    } else if (theParameter instanceof BaseIdentifierDt) {
        BaseIdentifierDt id = (BaseIdentifierDt) theParameter;
        system = id.getSystemElement().getValueAsString();
        code = (id.getValueElement().getValue());
    } else if (theParameter instanceof BaseCodingDt) {
        BaseCodingDt id = (BaseCodingDt) theParameter;
        system = id.getSystemElement().getValueAsString();
        code = (id.getCodeElement().getValue());
    } else {
        throw new IllegalArgumentException("Invalid token type: " + theParameter.getClass());
    }

    if (system != null && system.length() > ResourceIndexedSearchParamToken.MAX_LENGTH) {
        throw new InvalidRequestException("Parameter[" + theParamName + "] has system (" + system.length()
                + ") that is longer than maximum allowed (" + ResourceIndexedSearchParamToken.MAX_LENGTH + "): "
                + system);
    }

    if (code != null && code.length() > ResourceIndexedSearchParamToken.MAX_LENGTH) {
        throw new InvalidRequestException("Parameter[" + theParamName + "] has code (" + code.length()
                + ") that is longer than maximum allowed (" + ResourceIndexedSearchParamToken.MAX_LENGTH + "): "
                + code);
    }

    /*
     * Process token modifiers (:in, :below, :above)
     */

    List<VersionIndependentConcept> codes = null;
    if (modifier == TokenParamModifier.IN) {
        codes = myTerminologySvc.expandValueSet(code);
    } else if (modifier == TokenParamModifier.ABOVE) {
        system = determineSystemIfMissing(theParamName, code, system);
        codes = myTerminologySvc.findCodesAbove(system, code);
    } else if (modifier == TokenParamModifier.BELOW) {
        system = determineSystemIfMissing(theParamName, code, system);
        codes = myTerminologySvc.findCodesBelow(system, code);
    }

    if (codes != null) {
        if (codes.isEmpty()) {
            return null;
        }
        List<Predicate> orPredicates = new ArrayList<Predicate>();
        for (VersionIndependentConcept nextCode : codes) {
            Predicate systemPredicate = theBuilder.equal(theFrom.get("mySystem"), nextCode.getSystem());
            Predicate codePredicate = theBuilder.equal(theFrom.get("myValue"), nextCode.getCode());
            orPredicates.add(theBuilder.and(systemPredicate, codePredicate));
        }

        return theBuilder.or(orPredicates.toArray(new Predicate[orPredicates.size()]));
    }

    /*
     * Ok, this is a normal query
     */

    ArrayList<Predicate> singleCodePredicates = (new ArrayList<Predicate>());
    if (StringUtils.isNotBlank(system)) {
        singleCodePredicates.add(theBuilder.equal(theFrom.get("mySystem"), system));
    } else if (system == null) {
        // don't check the system
    } else {
        // If the system is "", we only match on null systems
        singleCodePredicates.add(theBuilder.isNull(theFrom.get("mySystem")));
    }

    if (StringUtils.isNotBlank(code)) {
        singleCodePredicates.add(theBuilder.equal(theFrom.get("myValue"), code));
    } else {
        /*
         * As of HAPI FHIR 1.5, if the client searched for a token with a system but no specified value this means to
         * match all tokens with the given value.
         * 
         * I'm not sure I agree with this, but hey.. FHIR-I voted and this was the result :)
         */
        // singleCodePredicates.add(theBuilder.isNull(theFrom.get("myValue")));
    }

    Predicate singleCode = theBuilder.and(toArray(singleCodePredicates));
    return singleCode;
}

From source file:nl.b3p.viewer.stripes.ApplicationActionBean.java

static Application findApplication(String name, String version) {
    EntityManager em = Stripersist.getEntityManager();
    if (name != null) {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery q = cb.createQuery(Application.class);
        Root<Application> root = q.from(Application.class);
        Predicate namePredicate = cb.equal(root.get("name"), name);
        Predicate versionPredicate = version != null ? cb.equal(root.get("version"), version)
                : cb.isNull(root.get("version"));
        q.where(cb.and(namePredicate, versionPredicate));
        try {//from w ww  .  ja v a2 s  .  co m
            return (Application) em.createQuery(q).getSingleResult();
        } catch (NoResultException nre) {
            String decodedName = StringUtil.urlDecode(name);
            if (!decodedName.equals(name)) {
                return findApplication(decodedName, version);
            }
        }
    }
    return null;
}

From source file:org.apache.ambari.server.orm.dao.ServiceConfigDAO.java

@RequiresSession
public List<ServiceConfigEntity> getLastServiceConfigVersionsForGroups(Collection<Long> configGroupIds) {
    if (configGroupIds == null || configGroupIds.isEmpty()) {
        return Collections.emptyList();
    }/*w  w  w .  ja  v a  2s.c o m*/
    CriteriaBuilder cb = entityManagerProvider.get().getCriteriaBuilder();
    CriteriaQuery<Tuple> cq = cb.createTupleQuery();
    Root<ServiceConfigEntity> groupVersion = cq.from(ServiceConfigEntity.class);

    cq.multiselect(groupVersion.get("groupId").alias("groupId"),
            cb.max(groupVersion.<Long>get("version")).alias("lastVersion"));
    cq.where(groupVersion.get("groupId").in(configGroupIds));
    cq.groupBy(groupVersion.get("groupId"));
    List<Tuple> tuples = daoUtils.selectList(entityManagerProvider.get().createQuery(cq));
    List<ServiceConfigEntity> result = new ArrayList<ServiceConfigEntity>();
    //subquery look to be very poor, no bulk select then, cache should help here as result size is naturally limited
    for (Tuple tuple : tuples) {
        CriteriaQuery<ServiceConfigEntity> sce = cb.createQuery(ServiceConfigEntity.class);
        Root<ServiceConfigEntity> sceRoot = sce.from(ServiceConfigEntity.class);

        sce.where(cb.and(cb.equal(sceRoot.get("groupId"), tuple.get("groupId")),
                cb.equal(sceRoot.get("version"), tuple.get("lastVersion"))));
        sce.select(sceRoot);
        result.add(daoUtils.selectSingle(entityManagerProvider.get().createQuery(sce)));
    }

    return result;
}

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  .c o 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;
}

From source file:org.apache.ranger.service.XTrxLogService.java

private Predicate generatePredicate(SearchCriteria searchCriteria, EntityManager em,
        CriteriaBuilder criteriaBuilder, Root<VXXTrxLog> rootEntityType) {
    Predicate predicate = criteriaBuilder.conjunction();
    Map<String, Object> paramList = searchCriteria.getParamList();
    if (CollectionUtils.isEmpty(paramList)) {
        return predicate;
    }//  www.j  av  a2s  .c  o m

    Metamodel entityMetaModel = em.getMetamodel();
    EntityType<VXXTrxLog> entityType = entityMetaModel.entity(VXXTrxLog.class);

    for (Map.Entry<String, Object> entry : paramList.entrySet()) {
        String key = entry.getKey();
        for (SearchField searchField : searchFields) {
            if (!key.equalsIgnoreCase(searchField.getClientFieldName())) {
                continue;
            }

            String fieldName = searchField.getFieldName();
            if (!StringUtils.isEmpty(fieldName)) {
                fieldName = fieldName.contains(".") ? fieldName.substring(fieldName.indexOf(".") + 1)
                        : fieldName;
            }

            Object paramValue = entry.getValue();
            boolean isListValue = false;
            if (paramValue != null && paramValue instanceof Collection) {
                isListValue = true;
            }

            // build where clause depending upon given parameters
            if (SearchField.DATA_TYPE.STRING.equals(searchField.getDataType())) {
                // build where clause for String datatypes
                SingularAttribute attr = entityType.getSingularAttribute(fieldName);
                if (attr != null) {
                    Predicate stringPredicate = null;
                    if (SearchField.SEARCH_TYPE.PARTIAL.equals(searchField.getSearchType())) {
                        String val = "%" + paramValue + "%";
                        stringPredicate = criteriaBuilder.like(rootEntityType.get(attr), val);
                    } else {
                        stringPredicate = criteriaBuilder.equal(rootEntityType.get(attr), paramValue);
                    }
                    predicate = criteriaBuilder.and(predicate, stringPredicate);
                }

            } else if (SearchField.DATA_TYPE.INT_LIST.equals(searchField.getDataType())
                    || isListValue && SearchField.DATA_TYPE.INTEGER.equals(searchField.getDataType())) {
                // build where clause for integer lists or integers datatypes
                Collection<Number> intValueList = null;
                if (paramValue != null && (paramValue instanceof Integer || paramValue instanceof Long)) {
                    intValueList = new ArrayList<Number>();
                    intValueList.add((Number) paramValue);
                } else {
                    intValueList = (Collection<Number>) paramValue;
                }
                for (Number value : intValueList) {
                    SingularAttribute attr = entityType.getSingularAttribute(fieldName);
                    if (attr != null) {
                        Predicate intPredicate = criteriaBuilder.equal(rootEntityType.get(attr), value);
                        predicate = criteriaBuilder.and(predicate, intPredicate);
                    }
                }

            } else if (SearchField.DATA_TYPE.DATE.equals(searchField.getDataType())) {
                // build where clause for date datatypes
                Date fieldValue = (Date) paramList.get(searchField.getClientFieldName());
                if (fieldValue != null && searchField.getCustomCondition() == null) {
                    SingularAttribute attr = entityType.getSingularAttribute(fieldName);
                    Predicate datePredicate = null;
                    if (SearchField.SEARCH_TYPE.LESS_THAN.equals(searchField.getSearchType())) {
                        datePredicate = criteriaBuilder.lessThan(rootEntityType.get(attr), fieldValue);
                    } else if (SearchField.SEARCH_TYPE.LESS_EQUAL_THAN.equals(searchField.getSearchType())) {
                        datePredicate = criteriaBuilder.lessThanOrEqualTo(rootEntityType.get(attr), fieldValue);
                    } else if (SearchField.SEARCH_TYPE.GREATER_THAN.equals(searchField.getSearchType())) {
                        datePredicate = criteriaBuilder.greaterThan(rootEntityType.get(attr), fieldValue);
                    } else if (SearchField.SEARCH_TYPE.GREATER_EQUAL_THAN.equals(searchField.getSearchType())) {
                        datePredicate = criteriaBuilder.greaterThanOrEqualTo(rootEntityType.get(attr),
                                fieldValue);
                    } else {
                        datePredicate = criteriaBuilder.equal(rootEntityType.get(attr), fieldValue);
                    }
                    predicate = criteriaBuilder.and(predicate, datePredicate);
                }
            }
        }
    }
    return predicate;
}

From source file:org.apache.wookie.beans.jpa.JPAPersistenceManager.java

@SuppressWarnings("unchecked")
public <T extends IBean> T[] findByValues(Class<T> beansInterface, Map<String, Object> values, String orderBy,
        boolean ascending) {
    // validate entity manager transaction
    if (entityManager == null) {
        throw new IllegalStateException("Transaction not initiated or already closed");
    }//from www  . j a v a  2s. com

    // validate bean interface
    Class<? extends IBean> beanClass = BEAN_INTERFACE_TO_CLASS_MAP.get(beansInterface);
    if (beanClass == null) {
        throw new IllegalArgumentException("Invalid bean interface specified");
    }

    // get persistent beans by criteria
    try {
        // construct query criteria
        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery<? extends IBean> criteriaQuery = criteriaBuilder.createQuery(beanClass);
        Root<? extends IBean> beanRoot = criteriaQuery.from(beanClass);
        if ((values != null) && !values.isEmpty()) {
            Predicate predicate = null;
            for (Map.Entry<String, Object> value : values.entrySet()) {
                Predicate valuePredicate = ((value.getValue() != null)
                        ? criteriaBuilder.equal(beanRoot.get(value.getKey()), value.getValue())
                        : criteriaBuilder.isNull(beanRoot.get(value.getKey())));
                predicate = ((predicate != null) ? criteriaBuilder.and(predicate, valuePredicate)
                        : valuePredicate);
            }
            criteriaQuery.where(predicate);
        }
        if (orderBy != null) {
            criteriaQuery.orderBy(ascending ? criteriaBuilder.asc(beanRoot.get(orderBy))
                    : criteriaBuilder.desc(beanRoot.get(orderBy)));
        }

        // invoke query
        Query query = entityManager.createQuery(criteriaQuery);
        List<? extends IBean> beansList = query.getResultList();
        if ((beansList != null) && !beansList.isEmpty()) {
            return beansList.toArray((T[]) Array.newInstance(beansInterface, beansList.size()));
        }
    } catch (Exception e) {
        logger.error("Unexpected exception: " + e, e);
    }
    return (T[]) Array.newInstance(beansInterface, 0);
}

From source file:org.apereo.portal.fragment.subscribe.dao.jpa.JpaUserFragmentSubscriptionDaoImpl.java

@Override
public void afterPropertiesSet() throws Exception {
    this.userIdParameter = this.createParameterExpression(Integer.TYPE, "userId");
    this.fragmentOwnerParameter = this.createParameterExpression(String.class, "fragmentOwner");

    this.findUserFragmentInfoByPersonQuery = this
            .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<UserFragmentSubscriptionImpl>>() {
                @Override/*ww w  .jav a 2s.c o  m*/
                public CriteriaQuery<UserFragmentSubscriptionImpl> apply(CriteriaBuilder cb) {
                    final CriteriaQuery<UserFragmentSubscriptionImpl> criteriaQuery = cb
                            .createQuery(UserFragmentSubscriptionImpl.class);
                    final Root<UserFragmentSubscriptionImpl> root = criteriaQuery
                            .from(UserFragmentSubscriptionImpl.class);
                    criteriaQuery.select(root);
                    criteriaQuery
                            .where(cb.equal(root.get(UserFragmentSubscriptionImpl_.userId), userIdParameter));

                    return criteriaQuery;
                }
            });

    this.findUserFragmentInfoByPersonAndOwnerQuery = this
            .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<UserFragmentSubscriptionImpl>>() {
                @Override
                public CriteriaQuery<UserFragmentSubscriptionImpl> apply(CriteriaBuilder cb) {
                    final CriteriaQuery<UserFragmentSubscriptionImpl> criteriaQuery = cb
                            .createQuery(UserFragmentSubscriptionImpl.class);
                    final Root<UserFragmentSubscriptionImpl> root = criteriaQuery
                            .from(UserFragmentSubscriptionImpl.class);
                    criteriaQuery.select(root);
                    criteriaQuery.where(
                            cb.and(cb.equal(root.get(UserFragmentSubscriptionImpl_.userId), userIdParameter),
                                    cb.equal(root.get(UserFragmentSubscriptionImpl_.fragmentOwner),
                                            fragmentOwnerParameter)));

                    return criteriaQuery;
                }
            });

    this.findUsersWithActiveSubscriptionsQuery = this
            .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<String>>() {
                @Override
                public CriteriaQuery<String> apply(CriteriaBuilder cb) {
                    final CriteriaQuery<String> criteriaQuery = cb.createQuery(String.class);
                    final Root<UserFragmentSubscriptionImpl> root = criteriaQuery
                            .from(UserFragmentSubscriptionImpl.class);
                    criteriaQuery.select(root.get(UserFragmentSubscriptionImpl_.createdBy));
                    criteriaQuery.where(cb.equal(root.get(UserFragmentSubscriptionImpl_.active), true));

                    return criteriaQuery;
                }
            });
}

From source file:org.apereo.portal.i18n.dao.jpa.JpaMessageDao.java

@Override
public void afterPropertiesSet() throws Exception {
    this.codeParameter = this.createParameterExpression(String.class, "code");
    this.localeParameter = this.createParameterExpression(Locale.class, "locale");

    this.findMessageByCodeAndLocaleQuery = this
            .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<MessageImpl>>() {
                @Override//www . j  a v  a 2s  .c o m
                public CriteriaQuery<MessageImpl> apply(CriteriaBuilder cb) {
                    final CriteriaQuery<MessageImpl> criteriaQuery = cb.createQuery(MessageImpl.class);
                    final Root<MessageImpl> root = criteriaQuery.from(MessageImpl.class);
                    criteriaQuery.select(root);
                    criteriaQuery.where(cb.and(cb.equal(root.get(MessageImpl_.code), codeParameter),
                            cb.equal(root.get(MessageImpl_.locale), localeParameter)));
                    criteriaQuery.orderBy(cb.asc(root.get(MessageImpl_.code)),
                            cb.asc(root.get(MessageImpl_.locale)));

                    return criteriaQuery;
                }
            });

    this.findMessageByCodeQuery = this
            .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<MessageImpl>>() {
                @Override
                public CriteriaQuery<MessageImpl> apply(CriteriaBuilder cb) {
                    final CriteriaQuery<MessageImpl> criteriaQuery = cb.createQuery(MessageImpl.class);
                    final Root<MessageImpl> root = criteriaQuery.from(MessageImpl.class);
                    criteriaQuery.select(root);
                    criteriaQuery.where(cb.equal(root.get(MessageImpl_.code), codeParameter));
                    criteriaQuery.orderBy(cb.asc(root.get(MessageImpl_.locale)));

                    return criteriaQuery;
                }
            });

    this.findMessageByLocaleQuery = this
            .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<MessageImpl>>() {
                @Override
                public CriteriaQuery<MessageImpl> apply(CriteriaBuilder cb) {
                    final CriteriaQuery<MessageImpl> criteriaQuery = cb.createQuery(MessageImpl.class);
                    final Root<MessageImpl> root = criteriaQuery.from(MessageImpl.class);
                    criteriaQuery.select(root);
                    criteriaQuery.where(cb.equal(root.get(MessageImpl_.locale), localeParameter));
                    criteriaQuery.orderBy(cb.asc(root.get(MessageImpl_.code)));

                    return criteriaQuery;
                }
            });

    this.findCodes = this.createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<String>>() {
        @Override
        public CriteriaQuery<String> apply(CriteriaBuilder cb) {
            final CriteriaQuery<String> criteriaQuery = cb.createQuery(String.class);
            final Root<MessageImpl> root = criteriaQuery.from(MessageImpl.class);
            criteriaQuery.select(root.get(MessageImpl_.code));
            criteriaQuery.groupBy(root.get(MessageImpl_.code));
            return criteriaQuery;
        }
    });
}

From source file:org.apereo.portal.persondir.dao.jpa.JpaLocalAccountDaoImpl.java

@Override
public List<ILocalAccountPerson> getPeople(LocalAccountQuery query) {
    final EntityManager entityManager = this.getEntityManager();
    final CriteriaBuilder cb = entityManager.getCriteriaBuilder();

    final CriteriaQuery<LocalAccountPersonImpl> criteriaQuery = cb.createQuery(LocalAccountPersonImpl.class);
    final Root<LocalAccountPersonImpl> accountRoot = criteriaQuery.from(LocalAccountPersonImpl.class);
    final CollectionJoin<LocalAccountPersonImpl, LocalAccountPersonAttributeImpl> attributes = accountRoot
            .join(LocalAccountPersonImpl_.attributes);
    final ListJoin<LocalAccountPersonAttributeImpl, String> attributeValues = attributes
            .join(LocalAccountPersonAttributeImpl_.values);

    //Due to the joins multiple rows are returned for each result
    criteriaQuery.distinct(true);//from w ww. j av  a2s  .c o m
    criteriaQuery.select(accountRoot);

    final List<Predicate> whereParts = new LinkedList<Predicate>();
    final Map<Parameter<String>, String> params = new LinkedHashMap<Parameter<String>, String>();

    // if a username has been specified, append it to the query
    if (query.getName() != null) {
        whereParts.add(cb.equal(accountRoot.get(LocalAccountPersonImpl_.name), this.nameParameter));
        params.put(this.nameParameter, query.getName());
    }

    //Build Predicate for each attribute being queried
    int paramCount = 0;
    for (Map.Entry<String, List<String>> entry : query.getAttributes().entrySet()) {
        final List<String> values = entry.getValue();
        if (values == null) {
            continue;
        }

        //For each value create a Predicate checking the attribute name and value together
        for (final String value : values) {
            if (StringUtils.isBlank(value)) {
                continue;
            }

            //Create Parameter objects for the name and value, stick them in the params map for later use
            final ParameterExpression<String> nameParam = this.createParameterExpression(String.class,
                    "attrName" + paramCount);
            final ParameterExpression<String> valueParam = this.createParameterExpression(String.class,
                    "attrValue" + paramCount);

            params.put(nameParam, entry.getKey());
            params.put(valueParam, "%" + value.toLowerCase() + "%");

            //Build the and(eq, like) predicate and add it to the list of predicates for the where clause
            whereParts.add(cb.and(cb.equal(attributes.get(LocalAccountPersonAttributeImpl_.name), nameParam),
                    cb.like(cb.lower(attributeValues.as(String.class)), valueParam)));

            paramCount++;
        }
    }

    //Add the Predicates to the where clause
    criteriaQuery.where(cb.or(whereParts.toArray(new Predicate[whereParts.size()])));

    //Create the query
    final TypedQuery<LocalAccountPersonImpl> jpaQuery = this.createCachedQuery(criteriaQuery);

    //Add all of the stored up parameters to the query
    for (Map.Entry<Parameter<String>, String> entry : params.entrySet()) {
        final Parameter<String> parameter = entry.getKey();
        final String value = entry.getValue();
        jpaQuery.setParameter(parameter, value);
    }

    final List<LocalAccountPersonImpl> accounts = jpaQuery.getResultList();
    return new ArrayList<ILocalAccountPerson>(accounts);
}

From source file:org.apereo.portal.portlet.dao.jpa.JpaMarketplaceRatingDao.java

/**
 * @param marketplaceRatingPK the primary key of the entity you want
 * @return an attached entity if found, null otherwise
 *///from w w  w.  ja va2 s.co m
@PortalTransactionalReadOnly
@OpenEntityManager(unitName = PERSISTENCE_UNIT_NAME)
public IMarketplaceRating getRating(MarketplaceRatingPK marketplaceRatingPK) {
    final MarketplaceRatingPK tempRatingPK = marketplaceRatingPK;
    MarketplaceRatingImpl temp = new MarketplaceRatingImpl();
    temp.setMarketplaceRatingPK(marketplaceRatingPK);
    final EntityManager entityManager = this.getEntityManager();
    if (entityManager.contains(temp)) {
        temp = entityManager.merge(temp);
        return temp;
    } else {
        final TypedQuery<MarketplaceRatingImpl> query = this.createQuery(
                this.createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<MarketplaceRatingImpl>>() {
                    @Override
                    public CriteriaQuery<MarketplaceRatingImpl> apply(CriteriaBuilder input) {
                        final CriteriaQuery<MarketplaceRatingImpl> criteriaQuery = input
                                .createQuery(MarketplaceRatingImpl.class);
                        final Root<MarketplaceRatingImpl> definitionRoot = criteriaQuery
                                .from(MarketplaceRatingImpl.class);
                        Predicate conditionUser = input.equal(
                                definitionRoot.get("marketplaceRatingPK").get("userName"),
                                tempRatingPK.getUserName());
                        Predicate conditionPortlet = input.equal(
                                definitionRoot.get("marketplaceRatingPK").get("portletDefinition"),
                                tempRatingPK.getPortletDefinition());
                        Predicate allConditions = input.and(conditionPortlet, conditionUser);
                        criteriaQuery.where(allConditions);
                        return criteriaQuery;
                    }
                }));
        List<MarketplaceRatingImpl> results = query.getResultList();
        if (!results.isEmpty()) {
            return results.get(0);
        } else {
            return null;
        }
    }
}