Example usage for javax.persistence Query getSingleResult

List of usage examples for javax.persistence Query getSingleResult

Introduction

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

Prototype

Object getSingleResult();

Source Link

Document

Execute a SELECT query that returns a single untyped result.

Usage

From source file:com.adeptj.modules.data.jpa.core.AbstractJpaRepository.java

@Override
public Object getScalarResult(String namedQuery, List<Object> posParams) {
    EntityManager em = JpaUtil.createEntityManager(this.getEntityManagerFactory());
    try {/*from   w w  w  .  j a  va 2s.c om*/
        Query query = em.createNamedQuery(namedQuery);
        JpaUtil.bindQueryParams(query, posParams);
        return query.getSingleResult();
    } catch (Exception ex) { // NOSONAR
        throw new JpaException(ex);
    } finally {
        JpaUtil.closeEntityManager(em);
    }
}

From source file:org.asqatasun.entity.dao.audit.ContentDAOImpl.java

@Override
public Long findNumberOfSSPContentFromAudit(Audit audit) {
    Query query = entityManager.createQuery(SELECT_DISTINCT_SSP + SSPImpl.class.getName() + " s"
            + " WHERE s.audit = :audit" + " AND s.httpStatusCode =:httpStatusCode");
    query.setParameter(AUDIT_KEY, audit);
    query.setParameter(HTTP_STATUS_CODE_KEY, HTTP_STATUS_OK);
    return (Long) query.getSingleResult();
}

From source file:org.opentides.dao.impl.BaseEntityDaoJpaImpl.java

/**
 * {@inheritDoc}// w  w w .  j  av  a  2  s  .  com
 */
@SuppressWarnings("unchecked")
@Override
public final T loadEntityModel(final ID id, final boolean filter, final boolean lock) {
    T entity;
    if (filter && securityFilter != null) {
        String filterClause = this.getSecurityFilter();
        String whereClause = doSQLAppend(filterClause, "obj.id = " + id);
        Query query = getEntityManager()
                .createQuery("from " + getEntityBeanType().getName() + " obj where " + whereClause);
        try {
            return (T) query.getSingleResult();
        } catch (NoResultException nre) {
            return null;
        }
    } else {
        entity = getEntityManager().find(getEntityBeanType(), id);
    }
    if (lock)
        getEntityManager().lock(entity, javax.persistence.LockModeType.WRITE);
    return entity;
}

From source file:org.syncope.core.persistence.dao.impl.UserSearchDAOImpl.java

@Override
public int count(final Set<Long> adminRoles, final NodeCond searchCondition) {

    List<Object> parameters = Collections.synchronizedList(new ArrayList<Object>());

    // 1. get the query string from the search condition
    StringBuilder queryString = getQuery(searchCondition, parameters);

    // 2. take into account administrative roles
    queryString.insert(0, "SELECT u.user_id FROM (");
    queryString.append(") u WHERE user_id NOT IN (");
    queryString.append(getAdminRolesFilter(adminRoles)).append(")");

    // 3. prepare the COUNT query
    queryString.insert(0, "SELECT COUNT(user_id) FROM (");
    queryString.append(") count_user_id");

    Query countQuery = entityManager.createNativeQuery(queryString.toString());
    fillWithParameters(countQuery, parameters);

    LOG.debug("Native count query\n{}\nwith parameters\n{}", queryString.toString(), parameters);

    int result = ((Number) countQuery.getSingleResult()).intValue();
    LOG.debug("Native count query result: {}", result);

    return result;
}

From source file:net.sf.gazpachoquest.qbe.NamedQueryUtil.java

public Object objectByNamedQuery(final SearchParameters sp) {
    if (sp == null || !sp.hasNamedQuery()) {
        throw new IllegalStateException(
                "Invalid search template provided: could not determine which namedQuery to use");
    }//from ww w.j  a  va2 s.c o  m

    Query query = entityManager.createNamedQuery(sp.getNamedQuery());
    String queryString = getQueryString(query);

    // append select count if needed
    if (queryString != null && queryString.toLowerCase(Locale.ENGLISH).startsWith("from")
            && !queryString.toLowerCase(Locale.ENGLISH).contains("count(")) {
        query = recreateQuery(query, "select count(*) " + queryString);
    }

    setQueryParameters(query, sp);

    if (logger.isDebugEnabled()) {
        logger.debug("objectNamedQuery " + sp.toString());
    }

    // execute
    Object result = query.getSingleResult();

    if (logger.isDebugEnabled()) {
        logger.debug(sp.getNamedQuery() + " returned a " + (result == null ? "null" : result.getClass())
                + " object");
        if (result instanceof Number) {
            logger.debug(sp.getNamedQuery() + " returned a number with value : " + result);
        }
    }

    return result;
}

From source file:com.impetus.ankush.common.dao.impl.GenericDaoJpa.java

/**
 * Gets the count.//  w ww . ja v a2s .  c  om
 * 
 * @param queryString
 *            the query string
 * @param parameterList
 *            the parameter list
 * @return the count
 */
private int getCount(String queryString, List<Object> parameterList) {
    Query query = this.entityManager.createQuery(queryString);
    if (parameterList != null) {
        assignQueryParameters(query, parameterList);
    }
    return ((Long) query.getSingleResult()).intValue();
}

From source file:com.sun.socialsite.business.impl.JPAGroupManagerImpl.java

public boolean isMember(Group group, Profile profile) throws SocialSiteException {
    Query query = strategy.getNamedQuery("GroupRelationship.getByGroupAndUserProfile");
    query.setParameter(1, group);/*from w  w w  .  j a  v  a  2 s.  co  m*/
    query.setParameter(2, profile);
    try {
        return (query.getSingleResult() != null);
    } catch (NoResultException e) {
        return false;
    }
}

From source file:com.sun.socialsite.userapi.UserManagerImpl.java

public void revokeRole(String roleName, User user) throws UserManagementException {
    if (roleName == null) {
        throw new UserManagementException("Cannot revoke role with null roleName");
    }/*from   ww w.  j  a va2  s  .co m*/
    if (user == null) {
        throw new UserManagementException("Cannot revoke role with null user");
    }

    Query query = getNamedQuery("UserRole.findByRoleName");
    query.setParameter("roleName", roleName);

    try {
        UserRole role = (UserRole) query.getSingleResult();
        Set<UserRole> userRoles = user.getRoles();
        userRoles.remove(role);
        user.setRoles(userRoles);
    } catch (NoResultException ex) {
        // no op
    }
}

From source file:com.sun.socialsite.userapi.UserManagerImpl.java

private UserRole getOrCreateRole(String roleName) throws PersistenceException {
    UserRole role = null;/*from   w ww .j a  va2  s . com*/
    try {
        Query query = getNamedQuery("UserRole.findByRoleName");
        query.setParameter("roleName", roleName);
        role = (UserRole) query.getSingleResult();
    } catch (NoResultException nre) {
        // create the role in database
        EntityManager em2 = null;
        try {
            em2 = getEmf().createEntityManager();
            em2.getTransaction().begin();
            UserRole newRole = new UserRole();
            newRole.setRoleName(roleName);
            em2.persist(newRole);
            em2.flush();
            em2.getTransaction().commit();
        } catch (PersistenceException pe) {
            if (em2 == null) {
                // If we couldn't even create an EntityManager, something is clearly wrong
                throw pe;
            } else {
                // Otherwise, ignore exception for now; the role may have been created in another thread
                if (em2.getTransaction().isActive())
                    em2.getTransaction().rollback();
            }
        } finally {
            if (em2 != null)
                em2.close();
        }
    }

    // If role is null, try again (since it _should_ now exist in the DB).
    if (role == null) {
        Query query = getNamedQuery("UserRole.findByRoleName");
        query.setParameter("roleName", roleName);
        role = (UserRole) query.getSingleResult();
    }

    return role;
}

From source file:com.telefonica.euro_iaas.sdc.dao.impl.ProductInstanceDaoJpaImpl.java

@SuppressWarnings("unchecked")
@Override//from w  w w .  j  a va2s.c o m
public ProductInstance findByProductInstanceName(String productInstanceName) throws EntityNotFoundException {

    // alternative return super.loadByField(ProductInstance.class, "name", productInstanceName);

    // Query query = entityManager.createQuery("select p from artifact " +

    // p join fetch p.productinstance where p.name = :name" );
    /*
     * SELECT * FROM productinstance LEFT JOIN artifact ON productinstance.id=artifact.productinstance_id;
     */
    // Query query = entityManager.createQuery
    // ("select p from ProductInstance p left join fetch p.artifact where p.name = '"+productInstanceName+"'");
    Query query = (Query) getEntityManager()
            .createQuery("select p from ProductInstance p  where p.name = '" + productInstanceName + "'");

    // where p.name = '" + productInstanceName+"'");

    // select claseA from A claseA left join fetch claseA.b claseB

    // Query query =
    // entityManager.createQuery("select p from EnvironmentInstance" +
    // " p join fetch p.tierInstances where p.name = :name" );

    // query.setParameter("name", productInstanceName);

    ProductInstance productInstance = null;
    try {
        productInstance = (ProductInstance) query.getSingleResult();
    } catch (NoResultException e) {
        String message = " No ProductInstance found in the database " + "with name: " + productInstanceName;
        System.out.println(message);
        throw new EntityNotFoundException(ProductInstance.class, "name", productInstanceName);
    }
    return productInstance;
}