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.querybyexample.jpa.GenericRepository.java

/**
 * Count the number of E instances./*  w  ww .  j a  v a2  s .  c om*/
 *
 * @param entity a sample entity whose non-null properties may be used as
 * search hint
 * @param searchParameters carries additional search information
 * @return the number of entities matching the search.
 */
@Transactional(readOnly = true)
public int findCount(E entity, SearchParameters sp) {
    checkNotNull(entity, "The entity cannot be null");
    checkNotNull(sp, "The searchParameters cannot be null");

    if (sp.hasNamedQuery()) {
        return byNamedQueryUtil.numberByNamedQuery(sp).intValue();
    }
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();

    CriteriaQuery<Long> criteriaQuery = builder.createQuery(Long.class);
    Root<E> root = criteriaQuery.from(type);

    if (sp.getDistinct()) {
        criteriaQuery = criteriaQuery.select(builder.countDistinct(root));
    } else {
        criteriaQuery = criteriaQuery.select(builder.count(root));
    }

    // predicate
    Predicate predicate = getPredicate(root, builder, entity, sp);
    if (predicate != null) {
        criteriaQuery = criteriaQuery.where(predicate);
    }

    orderByUtil.forceJoinOrder(root, sp);

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

    applyCacheHints(typedQuery, sp);
    Long count = typedQuery.getSingleResult();

    if (count != null) {
        return count.intValue();
    } else {
        log.warn("findCount returned null");
        return 0;
    }
}

From source file:com.qpark.eip.core.spring.statistics.dao.StatisticsLoggingDao.java

/**
 * Add the {@link SystemUserLogType} to the database.
 *
 * @param log// w w w  . ja  va 2 s.  com
 *            the {@link SystemUserLogType} to add.
 */
private void addChannelInvocation(final SystemUserLogType log) {
    /* Setup context and version. */
    log.setContext(this.getContextName());
    log.setVersion(this.getContextVersion());
    if (log.getUserName() != null && log.getUserName().trim().length() == 0) {
        log.setUserName(null);
    }

    /* Setup to search existing one. */
    final CriteriaBuilder cb = this.em.getCriteriaBuilder();
    final CriteriaQuery<SystemUserLogType> q = cb.createQuery(SystemUserLogType.class);
    final Root<SystemUserLogType> c = q.from(SystemUserLogType.class);

    final List<Predicate> predicates = new ArrayList<Predicate>();
    predicates.add(cb.equal(c.<String>get(SystemUserLogType_.context), log.getContext()));
    predicates.add(cb.equal(c.<String>get(SystemUserLogType_.version), log.getVersion()));
    if (log.getUserName() == null) {
        predicates.add(cb.isNull(c.<String>get(SystemUserLogType_.userName)));
    } else {
        predicates.add(cb.equal(c.<String>get(SystemUserLogType_.userName), log.getUserName()));
    }
    predicates.add(cb.equal(c.<String>get(SystemUserLogType_.serviceName), log.getServiceName()));
    predicates.add(cb.equal(c.<String>get(SystemUserLogType_.operationName), log.getOperationName()));
    predicates.add(cb.between(c.<Date>get(SystemUserLogType_.logDateItem), getDayStart(log.getLogDateItem()),
            getDayEnd(log.getLogDateItem())));

    q.where(predicates.toArray(new Predicate[predicates.size()]));
    q.orderBy(cb.desc(c.<Long>get(SystemUserLogType_.hjid)));
    TypedQuery<SystemUserLogType> typedQuery = this.em.createQuery(q);

    SystemUserLogType persistence = null;
    synchronized (StatisticsLoggingDao.class) {
        try {
            persistence = typedQuery.getSingleResult();
            if (persistence == null) {
                /* Not found -> persist */
                persistence = log;
                this.setupSystemUserLog(persistence, null);
                this.em.persist(persistence);
            } else {
                /* Found -> add and merge */
                this.setupSystemUserLog(persistence, log);
                this.em.merge(persistence);
            }
        } catch (final NoResultException e) {
            /* Not found -> persist */
            persistence = log;
            this.setupSystemUserLog(persistence, null);
            this.em.persist(persistence);
        } catch (final NonUniqueResultException e) {
            /* Found more */
            typedQuery = this.em.createQuery(q);
            final List<SystemUserLogType> list = typedQuery.getResultList();
            SystemUserLogType l;
            for (int i = 0; i < list.size(); i++) {
                l = list.get(i);
                if (persistence == null && l.getHjid() != null) {
                    persistence = l;
                    break;
                }
            }
            if (persistence != null) {
                /* Found more -> condense to first valid one -> merge. */
                this.setupSystemUserLog(persistence, log);
                for (int i = list.size() - 1; i >= 0; i--) {
                    l = list.get(i);
                    if (l != null && l.getHjid() != null) {
                        if (persistence.getHjid().equals(l.getHjid())) {
                        } else {
                            this.setupSystemUserLog(persistence, l);
                            list.remove(i);
                            this.em.remove(l);
                        }
                    }
                }
                this.em.merge(persistence);
            } else {
                /* Found more -> no valid one in list -> persist. */
                persistence = log;
                this.setupSystemUserLog(persistence, null);
                this.em.persist(persistence);
            }
        }
    }
    this.logger.debug("addChannelInvocation SystemUserLog {} {} {} {} {} {}",
            this.contextNameProvider.getContextName(), this.contextNameProvider.getContextVersion(),
            String.valueOf(persistence.getUserName()), persistence.getServiceName(),
            persistence.getOperationName(), persistence.getLogDate().toXMLFormat());
}

From source file:com.ushahidi.swiftriver.core.api.dao.impl.JpaBucketDao.java

public BucketDrop findBucketDrop(Long bucketId, Long dropId) {
    String qlString = "FROM BucketDrop WHERE bucket.id = :bucketId AND drop.id = :dropId";
    BucketDrop bucketDrop = null;//w  ww  .  ja v a  2 s . c  o m
    try {
        TypedQuery<BucketDrop> query = em.createQuery(qlString, BucketDrop.class);
        query.setParameter("bucketId", bucketId);
        query.setParameter("dropId", dropId);
        bucketDrop = query.getSingleResult();
    } catch (NoResultException e) {

    }

    return bucketDrop;
}

From source file:net.navasoft.madcoin.backend.model.controller.impl.StatusDataAccess.java

/**
 * Gets the by logical id./*ww  w  .ja  v  a2 s .  c om*/
 * 
 * @param idEntity
 *            the id entity
 * @return the by logical id
 * @since 2/09/2014, 09:31:47 PM
 */
@Override
public AppUserXStatus getByLogicalId(Serializable idEntity) {
    TypedQuery<AppUserXStatus> query = entityManager.createNamedQuery("AppUserXStatus.findByIdUser",
            AppUserXStatus.class);
    query.setParameter("idAppUser", ((Long) idEntity));
    return query.getSingleResult();
}

From source file:org.openmeetings.app.data.basic.Fieldmanagment.java

public long getNextFieldvaluesId() {
    TypedQuery<Long> q = em.createNamedQuery("getFieldCount", Long.class);
    return q.getSingleResult() + 1;
}

From source file:com.ushahidi.swiftriver.core.api.dao.impl.JpaRiverDao.java

public RiverDrop findRiverDrop(Long id, Long dropId) {
    String qlString = "FROM RiverDrop WHERE river.id = :riverId AND drop.id = :dropId";
    RiverDrop riverDrop = null;/*w  w w .j  av  a2  s  .  com*/

    try {
        TypedQuery<RiverDrop> query = em.createQuery(qlString, RiverDrop.class);
        query.setParameter("riverId", id);
        query.setParameter("dropId", dropId);
        riverDrop = query.getSingleResult();
    } catch (NoResultException e) {
        logger.debug("Drop {} does not exist in river {}", dropId, id);
    }

    return riverDrop;
}

From source file:net.navasoft.madcoin.backend.model.controller.impl.ApplicationUserDataAccess.java

/**
 * Gets the by logical id./*  w ww  . j  a v a  2 s . c  o  m*/
 * 
 * @param idEntity
 *            the id entity
 * @return the by logical id
 * @since 2/09/2014, 09:31:40 PM
 */
@Override
public AppUsers getByLogicalId(Serializable idEntity) {
    TypedQuery<AppUsers> query = entityManager.createNamedQuery("AppUsers.findByIdApplicationUsers",
            AppUsers.class);
    query.setParameter("idApplicationUsers", ((Long) idEntity));
    return query.getSingleResult();
}

From source file:com.qpark.eip.core.model.analysis.AnalysisDao.java

/**
 * Check if the {@link EnterpriseType} with given name and modelVersion
 * exists.// w  w w . j a  v  a 2 s . co  m
 *
 * @param name
 *            the name of the {@link EnterpriseType}.
 * @param modelVersion
 *            the version of the model.
 * @return <code>true</code> if exists, else <code>false</code>.
 */
@Transactional(value = EipModelAnalysisPersistenceConfig.TRANSACTION_MANAGER_NAME, propagation = Propagation.REQUIRED)
public boolean existsEnterprise(final String name, final String modelVersion) {
    boolean value = false;

    final CriteriaBuilder cb = this.em.getCriteriaBuilder();
    final CriteriaQuery<Long> q = cb.createQuery(Long.class);
    final Root<EnterpriseType> f = q.from(EnterpriseType.class);
    q.select(f.<Long>get(EnterpriseType_.hjid));
    q.where(cb.equal(f.<String>get(EnterpriseType_.name), name),
            cb.equal(f.<String>get(EnterpriseType_.modelVersion), modelVersion));
    final TypedQuery<Long> typedQuery = this.em.createQuery(q);
    try {
        final Long l = typedQuery.getSingleResult();
        if (l != null && l.longValue() != 0) {
            value = true;
        }
    } catch (final Exception e) {
        value = false;
    }
    return value;
}

From source file:org.openmeetings.app.data.file.dao.FileExplorerItemDaoImpl.java

public FileExplorerItem getFileExplorerItemsByExternalIdAndType(Long externalFileId, String externalType) {
    log.debug(".getFileExplorerItemsByExternalIdAndType() started");

    try {//  ww w .  ja v  a  2s.c o  m

        String hql = "SELECT c FROM FileExplorerItem c " + "WHERE c.externalFileId = :externalFileId "
                + "AND c.externalType LIKE :externalType";

        TypedQuery<FileExplorerItem> query = em.createQuery(hql, FileExplorerItem.class);
        query.setParameter("externalFileId", externalFileId);
        query.setParameter("externalType", externalType);

        FileExplorerItem fileExplorerList = null;
        try {
            fileExplorerList = query.getSingleResult();
        } catch (NoResultException ex) {
        }

        return fileExplorerList;
    } catch (Exception ex2) {
        log.error("[getFileExplorerItemsByExternalIdAndType]: ", ex2);
    }
    return null;
}

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

/**
 * /* w  w  w.j a va2s.  c om*/
 * list entity by criteriaInfo
 * 
 * @param criteriaInfo
 * @return 
 */
public PagedResult<T> findAll(CriteriaInfo criteriaInfo) {
    EntityManager em = getEntityManager();

    ParamInfo paramInfo = criteriaInfo.getParamInfo();
    PageInfo pageInfo = criteriaInfo.getPageInfo();
    SortInfo sortInfo = criteriaInfo.getSortInfo();

    StringBuilder from = new StringBuilder();
    from.append(String.format("%s t ", entityClass.getSimpleName()));

    StringBuilder where = new StringBuilder();
    Map<String, Object> paramMap = new HashMap<>();

    where = prepareWhereCondition(paramInfo, paramMap, where);

    StringBuilder orderBy = new StringBuilder(" ");
    if (sortInfo != null) {
        Iterator<SortItem> iterator = sortInfo.getSortItems().iterator();
        while (iterator.hasNext()) {
            SortItem item = iterator.next();
            orderBy.append("t.").append(item.getFieldName()).append(" ")
                    .append(item.isDescending() ? "desc" : "asc").append(",");
        }
        orderBy = new StringBuilder(orderBy.substring(0, orderBy.length() - 1));
        ;
    }

    String query = toSql(where, from, orderBy, false);
    String countquery = toSql(where, from, orderBy, true);

    TypedQuery<T> cq = em.createQuery(query, entityClass);
    //??
    TypedQuery<Long> countq = em.createQuery(countquery, Long.class);

    for (String key : paramMap.keySet()) {
        Object value = paramMap.get(key);
        cq.setParameter(key, value);
        countq.setParameter(key, value);
    }

    Long countResult = countq.getSingleResult();

    if (pageInfo != null) {
        cq.setFirstResult(pageInfo.getOffset());
        cq.setMaxResults(pageInfo.getSize());
    }

    return new PagedResult(cq.getResultList(), countResult == null ? 0 : countResult.intValue());
}