Example usage for javax.persistence TypedQuery getSingleResult

List of usage examples for javax.persistence TypedQuery getSingleResult

Introduction

In this page you can find the example usage for javax.persistence TypedQuery getSingleResult.

Prototype

X getSingleResult();

Source Link

Document

Execute a SELECT query that returns a single result.

Usage

From source file:org.broadleafcommerce.cms.admin.server.handler.StructuredContentItemCriteriaCustomPersistenceHandler.java

@Override
public Entity update(PersistencePackage persistencePackage, DynamicEntityDao dynamicEntityDao,
        RecordHelper helper) throws ServiceException {
    Entity entity = persistencePackage.getEntity();
    removeHtmlEncoding(entity);/*w  w  w  .j a v  a2  s  .c o  m*/
    try {
        PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective();
        Map<String, FieldMetadata> adminProperties = helper.getSimpleMergedProperties(
                StructuredContentItemCriteria.class.getName(), persistencePerspective);
        Object primaryKey = helper.getPrimaryKey(entity, adminProperties);
        StructuredContentItemCriteria adminInstance = (StructuredContentItemCriteria) dynamicEntityDao
                .retrieve(Class.forName(entity.getType()[0]), primaryKey);
        if (adminInstance.getStructuredContent().getLockedFlag()) {
            /*
            This may be an attempt to delete a target item criteria off an otherwise un-edited, production StructuredContent instance
             */
            CriteriaBuilder criteriaBuilder = dynamicEntityDao.getStandardEntityManager().getCriteriaBuilder();
            CriteriaQuery<StructuredContent> query = criteriaBuilder.createQuery(StructuredContent.class);
            Root<StructuredContentImpl> root = query.from(StructuredContentImpl.class);
            query.where(criteriaBuilder.and(criteriaBuilder.equal(root.get("archivedFlag"), Boolean.FALSE),
                    criteriaBuilder.equal(root.get("originalItemId"),
                            adminInstance.getStructuredContent().getId())));
            query.select(root);
            TypedQuery<StructuredContent> scQuery = dynamicEntityDao.getStandardEntityManager()
                    .createQuery(query);
            try {
                checkCriteria: {
                    StructuredContent myContent = scQuery.getSingleResult();
                    for (StructuredContentItemCriteria itemCriteria : myContent.getQualifyingItemCriteria()) {
                        if (itemCriteria.getOrderItemMatchRule().equals(adminInstance.getOrderItemMatchRule())
                                && itemCriteria.getQuantity().equals(adminInstance.getQuantity())) {
                            //manually set the values - otherwise unwanted properties will be set
                            itemCriteria.setOrderItemMatchRule(
                                    entity.findProperty("orderItemMatchRule").getValue());
                            itemCriteria
                                    .setQuantity(Integer.parseInt(entity.findProperty("quantity").getValue()));
                            adminInstance = itemCriteria;
                            break checkCriteria;
                        }
                    }
                    throw new RuntimeException("Unable to find an item criteria to update");
                }
            } catch (Exception e) {
                throw new IllegalArgumentException("Unable to update a locked record");
            }
        } else {
            adminInstance = (StructuredContentItemCriteria) helper.createPopulatedInstance(adminInstance,
                    entity, adminProperties, false);
        }
        adminInstance = (StructuredContentItemCriteria) dynamicEntityDao.merge(adminInstance);
        Entity adminEntity = helper.getRecord(adminProperties, adminInstance, null, null);

        return adminEntity;
    } catch (Exception e) {
        LOG.error("Unable to execute persistence activity", e);
        throw new ServiceException("Unable to update entity for " + entity.getType()[0], e);
    }
}

From source file:org.broadleafcommerce.cms.admin.server.handler.StructuredContentItemCriteriaCustomPersistenceHandler.java

@Override
public void remove(PersistencePackage persistencePackage, DynamicEntityDao dynamicEntityDao,
        RecordHelper helper) throws ServiceException {
    Entity entity = persistencePackage.getEntity();
    try {// www.ja  va2 s  .  co m
        PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective();
        Map<String, FieldMetadata> adminProperties = helper.getSimpleMergedProperties(
                StructuredContentItemCriteria.class.getName(), persistencePerspective);
        Object primaryKey = helper.getPrimaryKey(entity, adminProperties);
        StructuredContentItemCriteria adminInstance = (StructuredContentItemCriteria) dynamicEntityDao
                .retrieve(Class.forName(entity.getType()[0]), primaryKey);

        if (adminInstance.getStructuredContent().getLockedFlag()) {
            /*
            This may be an attempt to delete a target item criteria off an otherwise un-edited, production StructuredContent instance
             */
            CriteriaBuilder criteriaBuilder = dynamicEntityDao.getStandardEntityManager().getCriteriaBuilder();
            CriteriaQuery<StructuredContent> query = criteriaBuilder.createQuery(StructuredContent.class);
            Root<StructuredContentImpl> root = query.from(StructuredContentImpl.class);
            query.where(criteriaBuilder.and(criteriaBuilder.equal(root.get("archivedFlag"), Boolean.FALSE),
                    criteriaBuilder.equal(root.get("originalItemId"),
                            adminInstance.getStructuredContent().getId())));
            query.select(root);
            TypedQuery<StructuredContent> scQuery = dynamicEntityDao.getStandardEntityManager()
                    .createQuery(query);
            try {
                StructuredContent myContent = scQuery.getSingleResult();
                for (StructuredContentItemCriteria itemCriteria : myContent.getQualifyingItemCriteria()) {
                    if (itemCriteria.getOrderItemMatchRule().equals(adminInstance.getOrderItemMatchRule())
                            && itemCriteria.getQuantity().equals(adminInstance.getQuantity())) {
                        myContent.getQualifyingItemCriteria().remove(itemCriteria);
                        return;
                    }
                }
                throw new RuntimeException("Unable to find an item criteria to delete");
            } catch (Exception e) {
                throw new IllegalArgumentException("Unable to update a locked record");
            }
        }

        dynamicEntityDao.remove(adminInstance);
    } catch (Exception e) {
        LOG.error("Unable to execute persistence activity", e);
        throw new ServiceException("Unable to remove entity for " + entity.getType()[0], e);
    }
}

From source file:org.broadleafcommerce.common.i18n.dao.TranslationDaoImpl.java

@Override
public Long countTranslationEntries(TranslatedEntity entityType, ResultType stage) {
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Long> criteria = builder.createQuery(Long.class);
    Root<TranslationImpl> root = criteria.from(TranslationImpl.class);
    criteria.select(builder.count(root));
    List<Predicate> restrictions = new ArrayList<Predicate>();
    restrictions.add(builder.equal(root.get("entityType"), entityType.getFriendlyType()));
    try {//from  ww  w  .j av a 2 s  .c  o m
        if (extensionManager != null) {
            extensionManager.getProxy().setup(TranslationImpl.class, stage);
            extensionManager.getProxy().refineRetrieve(TranslationImpl.class, stage, builder, criteria, root,
                    restrictions);
        }
        criteria.where(restrictions.toArray(new Predicate[restrictions.size()]));

        TypedQuery<Long> query = em.createQuery(criteria);
        query.setHint(QueryHints.HINT_CACHEABLE, true);
        return query.getSingleResult();
    } finally {
        if (extensionManager != null) {
            extensionManager.getProxy().breakdown(TranslationImpl.class, stage);
        }
    }
}

From source file:org.broadleafcommerce.core.catalog.dao.ProductDaoImpl.java

@Override
public Product readProductByExternalId(String externalId) {
    TypedQuery<Product> query = new TypedQueryBuilder<Product>(Product.class, "product")
            .addRestriction("product.defaultSku.externalId", "=", externalId).toQuery(em);

    try {/*  www  . j a  va2s . c om*/
        return query.getSingleResult();
    } catch (NoResultException e) {
        return null;
    }
}

From source file:org.broadleafcommerce.core.catalog.dao.ProductDaoImpl.java

protected Long readCountAllActiveProductsInternal(Date currentDate) {
    // Set up the criteria query that specifies we want to return a Long
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Long> criteria = builder.createQuery(Long.class);

    // The root of our search is Product
    Root<ProductImpl> product = criteria.from(ProductImpl.class);

    // We need to filter on active date on the sku
    Join<Product, Sku> sku = product.join("defaultSku");

    // We want the count of products
    criteria.select(builder.count(product));

    // Ensure the product is currently active
    List<Predicate> restrictions = new ArrayList<Predicate>();
    attachActiveRestriction(currentDate, product, sku, restrictions);

    // Add the restrictions to the criteria query
    criteria.where(restrictions.toArray(new Predicate[restrictions.size()]));

    TypedQuery<Long> query = em.createQuery(criteria);
    query.setHint(QueryHints.HINT_CACHEABLE, true);
    query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog");

    return query.getSingleResult();
}

From source file:org.broadleafcommerce.core.offer.dao.OfferAuditDaoImpl.java

@Override
public Long countUsesByCustomer(Long customerId, Long offerId) {
    TypedQuery<Long> query = new TypedQueryBuilder<OfferAudit>(OfferAudit.class, "offerAudit")
            .addRestriction("offerAudit.customerId", "=", customerId)
            .addRestriction("offerAudit.offerId", "=", offerId).toCountQuery(em);

    Long result = query.getSingleResult();
    return result;
}

From source file:org.broadleafcommerce.core.offer.dao.OfferAuditDaoImpl.java

@Override
public Long countOfferCodeUses(Long offerCodeId) {
    TypedQuery<Long> query = new TypedQueryBuilder<OfferAudit>(OfferAudit.class, "offerAudit")
            .addRestriction("offerAudit.offerCodeId", "=", offerCodeId).toCountQuery(em);

    Long result = query.getSingleResult();
    return result;
}

From source file:org.cambillaum.jpapersistor.persistence.dao.AbstractGenericJPADAO.java

@Override
public CLASSTYPE findOne(TypedQuery<CLASSTYPE> query) {
    Validate.notNull(query, "query cannot be null");

    CLASSTYPE retrievedInstance = query.getSingleResult();
    return retrievedInstance;
}

From source file:org.cleverbus.core.common.dao.MessageDaoJpaImpl.java

@Override
public int getCountProcessingMessagesForFunnel(Collection<String> funnelValues, int idleInterval,
        String funnelCompId) {/*  w ww  . jav a  2s . co m*/
    Assert.notEmpty(funnelValues, "funnelValues must not be empty");
    Assert.hasText(funnelCompId, "funnelCompId must not be empty");

    String jSql = "SELECT COUNT(m) " + "FROM " + Message.class.getName() + " m " + "INNER JOIN m.funnels f "
            + "WHERE (m.state = '" + MsgStateEnum.PROCESSING + "' " + "         OR m.state = '"
            + MsgStateEnum.WAITING + "'" + "         OR m.state = '" + MsgStateEnum.WAITING_FOR_RES + "')"
            + "      AND m.startProcessTimestamp >= :startTime" + "      AND m.funnelComponentId = '"
            + funnelCompId + "'" + "      AND (";

    for (String funnelValue : funnelValues) {
        jSql += "f.funnelValue = '" + funnelValue + "' OR ";
    }
    //remove last or
    jSql = StringUtils.substringBeforeLast(jSql, " OR ");

    jSql += ")";

    TypedQuery<Number> q = em.createQuery(jSql, Number.class);
    q.setParameter("startTime", new Timestamp(DateUtils.addSeconds(new Date(), -idleInterval).getTime()));

    return q.getSingleResult().intValue();
}

From source file:org.easy.criteria.CriteriaProcessor.java

/**
 * Counts the result found for the given criteria
 * //from  ww  w. ja  va2 s  .  c o  m
 * @param criteria
 * @param distinct
 * @return
 */
public <T> long count(final CriteriaComposer<T> criteria, boolean distinct) {
    log.trace("CriteriaProcessor.count");

    Preconditions.checkNotNull(criteria);

    Class<T> forClass = criteria.getEntityClass();
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Long> criteriaQuery = criteriaBuilder.createQuery(Long.class);

    Root<T> root = criteriaQuery.from(forClass);

    log.debug("root =" + forClass.getName());

    if (distinct)
        criteriaQuery.select(criteriaBuilder.countDistinct(root));
    else
        criteriaQuery.select(criteriaBuilder.count(root));

    List<Predicate> predicates = new ArrayList<Predicate>();

    if (criteria != null) {
        criteria.generateJoins(root);
        criteria.generateWhere(criteriaBuilder, predicates);
    }

    criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()]));

    TypedQuery<Long> query = entityManager.createQuery(criteriaQuery);

    long result = query.getSingleResult();

    log.debug("CriteriaProcessor.count =" + result);

    return result;
}