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.syncope.core.persistence.dao.impl.RoleDAOImpl.java

@Override
public SyncopeRole find(final Long id) {
    TypedQuery<SyncopeRole> query = entityManager.createQuery("SELECT e FROM SyncopeRole e WHERE e.id = :id",
            SyncopeRole.class);
    query.setParameter("id", id);

    SyncopeRole result = null;/*from w  w w  . ja  va2 s .  co m*/
    try {
        result = query.getSingleResult();
    } catch (NoResultException e) {
    }

    return result;
}

From source file:eu.domibus.common.dao.MessageLogDao.java

public MessageStatus getMessageStatus(final String messageId) {

    final TypedQuery<MessageStatus> query = this.em.createNamedQuery("MessageLogEntry.getMessageStatus",
            MessageStatus.class);
    query.setParameter("MESSAGE_ID", messageId);
    try {/*  www  . ja v  a2s .com*/
        return query.getSingleResult();
    } catch (NoResultException e) {
        return MessageStatus.MESSAGE_NOT_FOUND;
    }
}

From source file:com.epam.ipodromproject.repository.jpa.JPAHorseRepository.java

@Override
public long getPagesOfHorses(String partOfName) {
    TypedQuery<Long> query = entityManager.createNamedQuery("Horse.findNumberOfHorsesByPartOfName", Long.class);
    StringBuilder partOfNameBuilder = new StringBuilder("%");
    query.setParameter("partOfName", partOfNameBuilder.append(partOfName).append("%").toString());
    long pages = 1;
    try {/*from   ww w  .j a v  a2 s  . c  om*/
        pages = query.getSingleResult();
    } catch (Exception e) {
        pages = (long) 1;
    }
    return pages;
}

From source file:com.qpark.eip.core.spring.lockedoperation.dao.LockedOperationDaoImpl.java

/**
 * @see com.qpark.eip.core.spring.lockedoperation.dao.LockableOperationDao#lockOperation(com.qpark.eip.core.spring.lockedoperation.LockableOperation)
 *//*  ww  w  .  ja v  a  2 s  .c  o  m*/
@Override
@Transactional(value = EipLockedoperationConfig.TRANSACTION_MANAGER_NAME, propagation = Propagation.REQUIRED)
public synchronized boolean lockOperation(final LockableOperation operation) {
    this.logger.debug("+lock# {} {} {}",
            new Object[] { this.hostName, operation.getUUID(), operation.getName() });
    if (this.firstRun) {
        this.unlockOperationOnServerStart();
        this.firstRun = false;
    }
    boolean locked = false;
    String logString = getOperationLockString(operation);
    OperationLockControllType value = null;
    CriteriaBuilder cb = this.em.getCriteriaBuilder();
    CriteriaQuery<OperationLockControllType> q = cb.createQuery(OperationLockControllType.class);
    Root<OperationLockControllType> c = q.from(OperationLockControllType.class);
    q.where(cb.equal(c.<String>get("operationName"), logString));
    TypedQuery<OperationLockControllType> typedQuery = this.em.createQuery(q);
    try {
        value = typedQuery.getSingleResult();
        this.logger.debug(" lock# opeation {} {} locked by: {} {}", new Object[] { operation.getUUID(),
                operation.getName(), value.getServerName(), value.getLockDate() });
    } catch (NoResultException e) {
        value = null;
    } catch (NonUniqueResultException e) {
        return false;
    }
    if (value == null) {
        value = new OperationLockControllType();
        value.setOperationName(logString);
        value.setServerName(this.hostName);
        value.setServerIpAddress(this.hostAddress);
        value.setLockDate(DateUtil.get(new Date()));
        this.em.persist(value);
        locked = true;
    }
    this.logger.debug("-lock# {} {} {} {}", new Object[] { this.hostName, locked ? "locked" : "not locked",
            operation.getUUID(), operation.getName() });
    return locked;
}

From source file:net.awired.generic.jpa.dao.impl.GenericDaoImpl.java

@Transactional(propagation = Propagation.SUPPORTS)
protected long count(TypedQuery<Long> query) {
    return query.getSingleResult();
}

From source file:com.olp.jpa.domain.docu.ut.repo.EmployeeRepositoryImpl.java

@Override
public EmployeeBean findByEmpNumber(String empNum) {

    IContext ctx = ContextManager.getContext();
    String tid = ctx.getTenantId();

    TypedQuery<EmployeeBean> query = getEntityManager().createNamedQuery("UtEmployeeBean.findByEmpCode",
            EmployeeBean.class);
    query.setParameter("empCode", empNum); // TODO: Sanitize input, although low risk due to binding
    query.setParameter("tenant", tid);

    EmployeeBean bean = query.getSingleResult();

    return (bean);
}

From source file:eu.europa.ec.fisheries.uvms.exchange.dao.bean.ExchangeLogDaoBean.java

@Override
public ExchangeLog getExchangeLogByGuid(String logGuid, TypeRefType typeRefType) throws ExchangeDaoException {
    try {/*  w  w w  .  ja  va  2  s .  c  o  m*/
        TypedQuery<ExchangeLog> query = em.createNamedQuery(ExchangeConstants.LOG_BY_GUID, ExchangeLog.class);
        query.setParameter("typeRefType", typeRefType);
        query.setParameter("guid", logGuid);
        return query.getSingleResult();
    } catch (NoResultException e) {
        LOG.error("[ Error when getting entity by ID. ] {}", e.getMessage());
        throw new NoEntityFoundException("[ Error when getting entity by ID. ]");
    } catch (Exception e) {
        LOG.error("[ Error when getting entity by ID. ] {}", e.getMessage());
        throw new ExchangeDaoException("[ Error when getting entity by ID. ] ");
    }
}

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

@Override
public StorageFile getStorageFile(User user, String fileId, Integer version) {
    TypedQuery<StorageFile> query = getEntityManager()
            .createQuery(// ww w . ja  va2  s.  co  m
                    "FROM StorageFile s WHERE s.fileId = :fileId AND s.version = :version AND s.user = :user",
                    StorageFile.class)
            .setParameter("fileId", fileId).setParameter("version", version).setParameter("user", user);

    return query.getSingleResult();
}

From source file:org.wte4j.impl.WordTemplateRepository.java

private PersistentTemplate getPersistentTemplate(String documentName, String language)
        throws NoResultException {

    String queryString = "select t from PersistentTemplate t where t.documentName=:documentName "
            + "and t.language= :language";
    TypedQuery<PersistentTemplate> query = em.createQuery(queryString, PersistentTemplate.class);
    query.setParameter("documentName", documentName);
    query.setParameter("language", language);
    return query.getSingleResult();
}

From source file:models.Group.java

/**
  * //from w w w  .j  ava  2s. co  m
  * 
  * @param page 1
  * @param pageSize ??
  * @param industryId Id?
  * @param privacy ???
  * @param skillTag ?
  * @param groupName ???
  * @param memberUserId ?Id?
  * @param isOwner ????
  * @param orderBy ??????SQL
  * @param isDesc ???
  * @return Page
 */
public static Page<Group> queryByPage(int page, int pageSize, Long industryId, GroupPriv privacy,
        String skillTag, String groupName, List<Type> typeList, Long memberUserId, Boolean isOwner,
        String orderBy, Boolean isDesc) {
    StringBuilder hql = new StringBuilder();
    Map<String, Object> paramMap = new HashMap<>();
    hql.append("from Group g ");
    if (memberUserId != null) {
        hql.append(" left join g.groupmembers gm where gm.userId = :memberUserId ");
        paramMap.put("memberUserId", memberUserId);
    } else {
        hql.append(" where 1 = 1");
    }
    if (memberUserId != null && isOwner != null) {
        hql.append(" and ((g.owner.userId ").append(isOwner ? " = " : " <> ")
                .append(" :ownerUserId and g.type = :hasOwnerType) or g.type <> :hasOwnerType) ");
        paramMap.put("hasOwnerType", Type.NORMAL);
        paramMap.put("ownerUserId", memberUserId);
    }
    if (CollectionUtils.isNotEmpty(typeList)) {
        hql.append(" and g.type in (:typeList) ");
        paramMap.put("typeList", typeList);
    }
    if (null != industryId) {
        hql.append(" and g.industry.id = :industryId ");
        paramMap.put("industryId", industryId);
    }
    if (null != privacy) {
        hql.append(" and g.groupPriv = :privacy ");
        paramMap.put("privacy", privacy);
    }
    if (StringUtils.isNotBlank(skillTag)) {
        hql.append(" and g.tags like :skillTag ");
        paramMap.put("skillTag", "%" + skillTag + "%");
    }
    if (StringUtils.isNotBlank(groupName)) {
        hql.append(" and g.groupName like :groupName ");
        paramMap.put("groupName", "%" + groupName + "%");
    }

    String countHql = "select count(g.id) " + hql.toString();

    // order
    if (StringUtils.isNotBlank(orderBy)) {
        hql.append(" order by g.");
        hql.append(orderBy);
        hql.append(BooleanUtils.isFalse(isDesc) ? " asc " : " desc ");
    } else {
        hql.append(" order by countMem desc, id desc");
    }
    hql.insert(0, "select g ");

    TypedQuery<Group> listTypedQuery = JPA.em().createQuery(hql.toString(), Group.class)
            .setFirstResult((page - 1) * pageSize).setMaxResults(pageSize);
    TypedQuery<Long> countTypedQuery = JPA.em().createQuery(countHql, Long.class);
    for (Entry<String, Object> e : paramMap.entrySet()) {
        listTypedQuery.setParameter(e.getKey(), e.getValue());
        countTypedQuery.setParameter(e.getKey(), e.getValue());
    }

    List<Group> resultList = listTypedQuery.getResultList();
    Long count = countTypedQuery.getSingleResult();

    return new Page<Group>(Constants.SUCESS, count, resultList);
}