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.kuali.rice.kew.doctype.dao.impl.DocumentTypeDAOJpa.java

@Override
public Integer getMaxVersionNumber(String docTypeName) {
    TypedQuery<Integer> query = getEntityManager().createNamedQuery("DocumentType.GetMaxVersionNumber",
            Integer.class);
    query.setParameter("docTypeName", docTypeName);
    return query.getSingleResult();
}

From source file:org.kuali.rice.kew.doctype.dao.impl.DocumentTypeDAOJpa.java

@Override
public String findDocumentTypeIdByName(String documentTypeName) {
    TypedQuery<String> query = getEntityManager().createNamedQuery("DocumentType.GetIdByName", String.class);
    query.setParameter("docTypeName", documentTypeName);
    try {/*from w  w w  .  ja  v a  2s .  c o  m*/
        return query.getSingleResult();
    } catch (NoResultException e) {
        return null;
    }
}

From source file:org.kuali.rice.kew.doctype.dao.impl.DocumentTypeDAOJpa.java

@Override
public String findDocumentTypeNameById(String documentTypeId) {
    TypedQuery<String> query = getEntityManager().createNamedQuery("DocumentType.FindDocumentTypeNameById",
            String.class);
    query.setParameter("documentTypeId", documentTypeId);
    try {/* ww  w .  java  2 s . c  o  m*/
        return query.getSingleResult();
    } catch (NoResultException e) {
        return null;
    }
}

From source file:org.kuali.rice.kew.doctype.dao.impl.DocumentTypeDAOJpa.java

@Override
public DocumentType findDocumentTypeByDocumentId(String documentId) {
    TypedQuery<DocumentType> query = getEntityManager()
            .createNamedQuery("DocumentType.GetDocumentTypeByDocumentId", DocumentType.class);
    query.setParameter("documentId", documentId);
    try {/*from w  w  w .  j  a  v  a2 s. co m*/
        return query.getSingleResult();
    } catch (NoResultException e) {
        return null;
    }
}

From source file:org.medici.bia.dao.image.ImageDAOJpaImpl.java

/**
 * {@inheritDoc}//from   w  w w . j av a2  s .co  m
 */
@SuppressWarnings("rawtypes")
@Override
public Page findImages(Integer volNum, String volLetExt, PaginationFilter paginationFilter)
        throws PersistenceException {
    // Create criteria objects
    CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();

    Page page = new Page(paginationFilter);

    if (paginationFilter.getTotal() == null) {
        CriteriaQuery<Long> criteriaQueryCount = criteriaBuilder.createQuery(Long.class);
        Root<Image> rootCount = criteriaQueryCount.from(Image.class);
        criteriaQueryCount.select(criteriaBuilder.count(rootCount));

        // Define predicate's elements
        ParameterExpression<Integer> parameterVolNum = criteriaBuilder.parameter(Integer.class, "volNum");
        ParameterExpression<String> parameterVolLeText = StringUtils.isEmpty("volLetExt") ? null
                : criteriaBuilder.parameter(String.class, "volLetExt");

        criteriaQueryCount
                .where(criteriaBuilder.and(criteriaBuilder.equal(rootCount.get("volNum"), parameterVolNum),
                        StringUtils.isEmpty(volLetExt) ? criteriaBuilder.isNull(rootCount.get("volLetExt"))
                                : criteriaBuilder.equal(rootCount.get("volLetExt"), parameterVolLeText)));

        TypedQuery typedQueryCount = getEntityManager().createQuery(criteriaQueryCount);
        typedQueryCount.setParameter("volNum", volNum);
        if (!StringUtils.isEmpty(volLetExt)) {
            typedQueryCount.setParameter("volLetExt", volLetExt);
        }
        page.setTotal(new Long((Long) typedQueryCount.getSingleResult()));
    }

    CriteriaQuery<Image> criteriaQuery = criteriaBuilder.createQuery(Image.class);
    Root<Image> root = criteriaQuery.from(Image.class);

    // Define predicate's elements
    ParameterExpression<Integer> parameterVolNum = criteriaBuilder.parameter(Integer.class, "volNum");
    ParameterExpression<String> parameterVolLeText = StringUtils.isEmpty("volLetExt") ? null
            : criteriaBuilder.parameter(String.class, "volLetExt");

    //We need to duplicate predicates beacause they are link to Root element
    criteriaQuery.where(criteriaBuilder.and(criteriaBuilder.equal(root.get("volNum"), parameterVolNum),
            StringUtils.isEmpty(volLetExt) ? criteriaBuilder.isNull(root.get("volLetExt"))
                    : criteriaBuilder.equal(root.get("volLetExt"), parameterVolLeText)));

    // Set values in predicate's elements  
    TypedQuery<Image> typedQuery = getEntityManager().createQuery(criteriaQuery);
    typedQuery.setParameter("volNum", volNum);
    if (!StringUtils.isEmpty(volLetExt)) {
        typedQuery.setParameter("volLetExt", volLetExt);
    }

    //Pagination will work with index [1 ... total] and not [0 ... total1-] 
    typedQuery.setFirstResult(paginationFilter.getFirstRecord() - 1);
    typedQuery.setMaxResults(paginationFilter.getLength());
    page.setList(typedQuery.getResultList());

    return page;
}

From source file:org.medici.bia.dao.image.ImageDAOJpaImpl.java

/**
 * {@inheritDoc}/*w w w  .  ja  v a  2  s .co  m*/
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public FoliosInformations findVolumeFoliosInformations(Integer volNum, String volLetExt)
        throws PersistenceException {
    FoliosInformations foliosInformations = new FoliosInformations();

    CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();

    CriteriaQuery<Long> criteriaQueryCount = criteriaBuilder.createQuery(Long.class);
    Root<Image> rootCount = criteriaQueryCount.from(Image.class);
    criteriaQueryCount.select(criteriaBuilder.count(rootCount));

    // Define predicate's elements
    ParameterExpression<Integer> parameterVolNum = criteriaBuilder.parameter(Integer.class, "volNum");
    ParameterExpression<String> parameterVolLeText = StringUtils.isEmpty("volLetExt") ? null
            : criteriaBuilder.parameter(String.class, "volLetExt");

    criteriaQueryCount
            .where(criteriaBuilder.and(criteriaBuilder.equal(rootCount.get("volNum"), parameterVolNum),
                    StringUtils.isEmpty(volLetExt) ? criteriaBuilder.isNull(rootCount.get("volLetExt"))
                            : criteriaBuilder.equal(rootCount.get("volLetExt"), parameterVolLeText)));

    TypedQuery typedQueryCount = getEntityManager().createQuery(criteriaQueryCount);
    typedQueryCount.setParameter("volNum", volNum);
    if (!StringUtils.isEmpty(volLetExt))
        typedQueryCount.setParameter("volLetExt", volLetExt);
    foliosInformations.setTotal((Long) typedQueryCount.getSingleResult());

    StringBuilder stringBuilder = new StringBuilder(
            "SELECT imageType, imageRectoVerso, max(imageProgTypeNum) FROM Image WHERE volNum=:volNum and volLetExt ");
    if (!StringUtils.isEmpty(volLetExt))
        stringBuilder.append(" = :volLetExt");
    else
        stringBuilder.append(" is null");
    stringBuilder.append(" GROUP BY imageType, imageRectoVerso");

    Query query = getEntityManager().createQuery(stringBuilder.toString());
    query.setParameter("volNum", volNum);
    if (!StringUtils.isEmpty(volLetExt)) {
        query.setParameter("volLetExt", volLetExt);
    }

    List<Object[]> result = (List<Object[]>) query.getResultList();

    // We init every partial-total
    foliosInformations.setTotalRubricario(new Long(0));
    foliosInformations.setTotalCarta(new Long(0));
    foliosInformations.setTotalAppendix(new Long(0));
    foliosInformations.setTotalOther(new Long(0));
    foliosInformations.setTotalGuardia(new Long(0));
    foliosInformations.setTotalMissingFolios(0);
    // We set new partial-total values 
    for (int i = 0; i < result.size(); i++) {
        // This is an array defined as [ImageType, Count by ImageType]
        Object[] singleGroup = result.get(i);

        if (((ImageType) singleGroup[0]).equals(ImageType.R)) {
            if (foliosInformations.getTotalRubricario() < new Long(singleGroup[2].toString())) {
                foliosInformations.setTotalRubricario(new Long(singleGroup[2].toString()));
            }
        } else if (((ImageType) singleGroup[0]).equals(ImageType.C)) {
            if (foliosInformations.getTotalCarta() < new Long(singleGroup[2].toString())) {
                foliosInformations.setTotalCarta(new Long(singleGroup[2].toString()));
            }
        } else if (((ImageType) singleGroup[0]).equals(ImageType.A)) {
            if (foliosInformations.getTotalAppendix() < new Long(singleGroup[2].toString())) {
                foliosInformations.setTotalAppendix(new Long(singleGroup[2].toString()));
            }
        } else if (((ImageType) singleGroup[0]).equals(ImageType.O)) {
            if (foliosInformations.getTotalOther() < new Long(singleGroup[2].toString())) {
                foliosInformations.setTotalOther(new Long(singleGroup[2].toString()));
            }
        } else if (((ImageType) singleGroup[0]).equals(ImageType.G)) {
            if (foliosInformations.getTotalGuardia() < new Long(singleGroup[2].toString())) {
                foliosInformations.setTotalGuardia(new Long(singleGroup[2].toString()));
            }
        }
    }

    // Calculating missing folios start
    stringBuilder = new StringBuilder(
            "SELECT DISTINCT(imageProgTypeNum) FROM Image WHERE volNum = :volNum AND volLetExt ");
    if (!StringUtils.isEmpty(volLetExt))
        stringBuilder.append(" = :volLetExt");
    else
        stringBuilder.append(" IS NULL");
    stringBuilder.append(" AND imageType = 'C'"); // we search only for folios
    stringBuilder.append(" ORDER BY imageProgTypeNum ASC");

    query = getEntityManager().createQuery(stringBuilder.toString());
    query.setParameter("volNum", volNum);
    if (!StringUtils.isEmpty(volLetExt)) {
        query.setParameter("volLetExt", volLetExt);
    }
    List<Integer> foliosOnVolume = (List<Integer>) query.getResultList();

    for (long i = 1; i <= foliosInformations.getTotalCarta(); i++) {
        for (int j = 0; j < foliosOnVolume.size(); j++) {
            if (foliosOnVolume.get(j) == i) {
                break;
            } else if (foliosOnVolume.get(j) > i) {
                foliosInformations.setTotalMissingFolios(foliosInformations.getTotalMissingFolios() + 1);
                //LP : Missing numbering is first counter!!!!
                foliosInformations.getMissingNumberingFolios().add(((Long) i).intValue());
                break;
            }
        }

    }
    // Calculating missing folios end

    //Extracting misnumbered Folios...
    stringBuilder = new StringBuilder(
            "SELECT concat(imageProgTypeNum, missedNumbering) FROM Image WHERE volNum=:volNum and volLetExt ");
    if (!StringUtils.isEmpty(volLetExt))
        stringBuilder.append(" = :volLetExt");
    else
        stringBuilder.append(" is null");
    stringBuilder.append(" and missedNumbering is not null ORDER BY imageProgTypeNum ASC");

    query = getEntityManager().createQuery(stringBuilder.toString());
    query.setParameter("volNum", volNum);
    if (!StringUtils.isEmpty(volLetExt)) {
        query.setParameter("volLetExt", volLetExt);
    }

    foliosInformations.setMisnumberedFolios((List<String>) query.getResultList());

    return foliosInformations;
}

From source file:org.medici.bia.dao.image.ImageDAOJpaImpl.java

/**
 * This method updates every totals in input.
 * /*from   w w  w  .  j a  v a 2s  .  c  o  m*/
 * @param explorer input object to be update.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
private <T extends VolumeExplorer> void updateExplorerTotals(T explorer) {
    CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();

    CriteriaQuery<Long> criteriaQueryCount = criteriaBuilder.createQuery(Long.class);
    Root<Image> rootCount = criteriaQueryCount.from(Image.class);
    criteriaQueryCount.select(criteriaBuilder.count(rootCount));

    // Define predicate's elements
    ParameterExpression<Integer> parameterVolNum = criteriaBuilder.parameter(Integer.class, "volNum");
    ParameterExpression<String> parameterVolLeText = StringUtils.isEmpty("volLetExt") ? null
            : criteriaBuilder.parameter(String.class, "volLetExt");

    criteriaQueryCount
            .where(criteriaBuilder.and(criteriaBuilder.equal(rootCount.get("volNum"), parameterVolNum),
                    StringUtils.isEmpty(explorer.getVolLetExt())
                            ? criteriaBuilder.isNull(rootCount.get("volLetExt"))
                            : criteriaBuilder.equal(rootCount.get("volLetExt"), parameterVolLeText)));

    TypedQuery typedQueryCount = getEntityManager().createQuery(criteriaQueryCount);
    typedQueryCount.setParameter("volNum", explorer.getVolNum());
    if (!StringUtils.isEmpty(explorer.getVolLetExt()))
        typedQueryCount.setParameter("volLetExt", explorer.getVolLetExt());
    explorer.setTotal((Long) typedQueryCount.getSingleResult());

    StringBuilder stringBuilder = new StringBuilder(
            "SELECT imageType, imageRectoVerso, max(imageProgTypeNum) FROM Image WHERE volNum=:volNum and volLetExt ");
    if (!StringUtils.isEmpty(explorer.getVolLetExt()))
        stringBuilder.append(" = :volLetExt");
    else
        stringBuilder.append(" is null");
    stringBuilder.append(" group by imageType, imageRectoVerso");

    Query query = getEntityManager().createQuery(stringBuilder.toString());
    query.setParameter("volNum", explorer.getVolNum());
    if (!StringUtils.isEmpty(explorer.getVolLetExt())) {
        query.setParameter("volLetExt", explorer.getVolLetExt());
    }

    List<Object[]> result = (List<Object[]>) query.getResultList();

    // We init every partial-total
    explorer.setTotalRubricario(new Long(0));
    explorer.setTotalCarta(new Long(0));
    explorer.setTotalAppendix(new Long(0));
    explorer.setTotalOther(new Long(0));
    explorer.setTotalGuardia(new Long(0));

    // We set new partial-total values 
    for (int i = 0; i < result.size(); i++) {
        // This is an array defined as [ImageType, Count by ImageType]
        Object[] singleGroup = result.get(i);

        if (((ImageType) singleGroup[0]).equals(ImageType.R)) {
            if (explorer.getTotalRubricario() < new Long(singleGroup[2].toString())) {
                explorer.setTotalRubricario(new Long(singleGroup[2].toString()));
            }
        } else if (((ImageType) singleGroup[0]).equals(ImageType.C)) {
            if (explorer.getTotalCarta() < new Long(singleGroup[2].toString())) {
                explorer.setTotalCarta(new Long(singleGroup[2].toString()));
            }
        } else if (((ImageType) singleGroup[0]).equals(ImageType.A)) {
            if (explorer.getTotalAppendix() < new Long(singleGroup[2].toString())) {
                explorer.setTotalAppendix(new Long(singleGroup[2].toString()));
            }
        } else if (((ImageType) singleGroup[0]).equals(ImageType.O)) {
            if (explorer.getTotalOther() < new Long(singleGroup[2].toString())) {
                explorer.setTotalOther(new Long(singleGroup[2].toString()));
            }
        } else if (((ImageType) singleGroup[0]).equals(ImageType.G)) {
            if (explorer.getTotalGuardia() < new Long(singleGroup[2].toString())) {
                explorer.setTotalGuardia(new Long(singleGroup[2].toString()));
            }
        }
    }
}

From source file:org.medici.bia.dao.volume.VolumeDAOJpaImpl.java

/**
 * {@inheritDoc}//from  ww  w . j av  a 2s.c  om
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public Page searchVolumes(String text, PaginationFilter paginationFilter) throws PersistenceException {
    // Create criteria objects
    CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();

    Page page = new Page(paginationFilter);

    if (paginationFilter.getTotal() == null) {
        CriteriaQuery<Long> criteriaQueryCount = criteriaBuilder.createQuery(Long.class);
        Root<Volume> rootCount = criteriaQueryCount.from(Volume.class);
        criteriaQueryCount.select(criteriaBuilder.count(rootCount));

        List<Predicate> predicates = new ArrayList<Predicate>();
        predicates.add(
                criteriaBuilder.like((Expression) rootCount.get("serieList").get("title"), "%" + text + "%"));
        predicates.add(criteriaBuilder.like((Expression) rootCount.get("serieList").get("subTitle1"),
                "%" + text + "%"));
        predicates.add(criteriaBuilder.like((Expression) rootCount.get("serieList").get("subTitle2"),
                "%" + text + "%"));
        predicates.add(criteriaBuilder.like((Expression) rootCount.get("orgNotes"), "%" + text + "%"));
        predicates.add(criteriaBuilder.like((Expression) rootCount.get("recips"), "%" + text + "%"));
        predicates.add(criteriaBuilder.like((Expression) rootCount.get("researcher"), "%" + text + "%"));
        predicates.add(criteriaBuilder.like((Expression) rootCount.get("senders"), "%" + text + "%"));

        //If we omiss criteriaBuilder.or every predicate is in conjunction with others  
        criteriaQueryCount.where(criteriaBuilder.or(predicates.toArray(new Predicate[] {})));

        TypedQuery typedQueryCount = getEntityManager().createQuery(criteriaQueryCount);
        page.setTotal(new Long((Long) typedQueryCount.getSingleResult()));
    }

    CriteriaQuery<Volume> criteriaQuery = criteriaBuilder.createQuery(Volume.class);
    Root<Volume> root = criteriaQuery.from(Volume.class);

    //We need to duplicate predicates beacause they are link to Root element
    List<Predicate> predicates = new ArrayList<Predicate>();
    predicates.add(criteriaBuilder.like((Expression) root.get("serieList").get("title"), "%" + text + "%"));
    predicates.add(criteriaBuilder.like((Expression) root.get("serieList").get("subTitle1"), "%" + text + "%"));
    predicates.add(criteriaBuilder.like((Expression) root.get("serieList").get("subTitle2"), "%" + text + "%"));
    predicates.add(criteriaBuilder.like((Expression) root.get("orgNotes"), "%" + text + "%"));
    predicates.add(criteriaBuilder.like((Expression) root.get("recips"), "%" + text + "%"));
    predicates.add(criteriaBuilder.like((Expression) root.get("researcher"), "%" + text + "%"));
    predicates.add(criteriaBuilder.like((Expression) root.get("senders"), "%" + text + "%"));

    //If we omiss criteriaBuilder.or every predicate is in conjunction with others  
    criteriaQuery.where(criteriaBuilder.or(predicates.toArray(new Predicate[] {})));
    criteriaQuery.orderBy(criteriaBuilder.asc(root.get("summaryId")));

    // Set values in predicate's elements  
    TypedQuery<Volume> typedQuery = getEntityManager().createQuery(criteriaQuery);
    typedQuery.setFirstResult(paginationFilter.getFirstRecord());
    typedQuery.setMaxResults(paginationFilter.getLength());
    page.setList(typedQuery.getResultList());

    return page;
}

From source file:org.meveo.service.admin.impl.MeveoModuleService.java

public void loadModuleItem(MeveoModuleItem item, Provider provider) {

    BusinessEntity entity = null;/*from  w w w  .  j  ava2  s . c o  m*/
    if (CustomFieldTemplate.class.getName().equals(item.getItemClass())) {
        entity = customFieldTemplateService.findByCodeAndAppliesTo(item.getItemCode(), item.getAppliesTo(),
                provider);

    } else {

        String sql = "select mi from " + item.getItemClass()
                + " mi where mi.code=:code and mi.provider=:provider";
        TypedQuery<BusinessEntity> query = getEntityManager().createQuery(sql, BusinessEntity.class);
        query.setParameter("code", item.getItemCode());
        query.setParameter("provider", provider);
        try {
            entity = query.getSingleResult();

        } catch (NoResultException | NonUniqueResultException e) {
            log.error("Failed to find a module item {}. Reason: {}", item, e.getClass().getSimpleName());
            return;
        } catch (Exception e) {
            log.error("Failed to find a module item {}", item, e);
            return;
        }
    }
    item.setItemEntity(entity);

}

From source file:org.opencastproject.messages.MailService.java

/**
 * Get the current logged in user's signature
 * @return The message signature//from  ww  w  . j av  a2  s. co  m
 * @throws UserSettingsServiceException
 */
public MessageSignature getCurrentUsersSignature() throws MailServiceException, NotFoundException {
    EntityManager em = null;
    try {
        em = emf.createEntityManager();
        String orgId = securityService.getOrganization().getId();
        String username = securityService.getUser().getUsername();
        TypedQuery<MessageSignatureDto> q = em
                .createNamedQuery("MessageSignature.findByCreator", MessageSignatureDto.class)
                .setParameter("username", username).setParameter("org", orgId);
        MessageSignatureDto messageSignatureDto = q.getSingleResult();
        return messageSignatureDto.toMessageSignature(userDirectoryService);
    } catch (NoResultException e) {
        throw new NotFoundException(e);
    } catch (Exception e) {
        logger.error("Could not get message signatures: {}", ExceptionUtils.getStackTrace(e));
        throw new MailServiceException(e);
    } finally {
        if (em != null)
            em.close();
    }
}