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.ushahidi.swiftriver.core.api.dao.impl.JpaRiverDao.java

/**
 * @see {@link RiverDao#findCollaborator(Long, Long)}
 *//*from   www .ja v a 2 s.c o  m*/
public RiverCollaborator findCollaborator(Long riverId, Long accountId) {
    String sql = "FROM RiverCollaborator rc " + "WHERE rc.account.id = :accountId "
            + "AND rc.river.id =:riverId";

    Query query = this.em.createQuery(sql);
    query.setParameter("accountId", accountId);
    query.setParameter("riverId", riverId);

    RiverCollaborator rc = null;
    try {
        rc = (RiverCollaborator) query.getSingleResult();
    } catch (Exception e) {
        // Do nothing;
    }

    return rc;
}

From source file:com.exp.tracker.services.impl.JpaUserService.java

@Transactional
public UserBean addUser(UserBean ub, RequestContext ctx) {
    UserBean newUb = null;// w w  w .  j  a v a 2 s  .  c o  m
    boolean userExists = true;
    // first find match
    Query queryFindMatch = em.createNamedQuery("findUserMatch");
    queryFindMatch.setParameter("username", ub.getUsername());
    // queryFindMatch.setParameter("emailId", ub.getEmailId());
    @SuppressWarnings("unused")
    UserEntity ue = null;
    try {
        ue = (UserEntity) queryFindMatch.getSingleResult();
    } catch (NoResultException nre) {
        if (logger.isDebugEnabled()) {
            logger.debug("User Id does not exist, thus can be added - " + ub.getUsername() + nre.getMessage());
        }
        userExists = false;
    }

    if (!userExists) {
        UserEntity ue1 = ub.getUserEntity();
        Calendar calendar = Calendar.getInstance();
        String newPassword = ub.getPassword();
        if (null == newPassword) {
            newPassword = RandomStringUtils.random(8, true, true);
        }
        // save hashed with salt
        ue1.setPassword(passwordEncoder.getHash(ub.getUsername(), newPassword));
        ue1.setCreatedDate(calendar.getTime());
        ue1.setPasswordChangeNeeded(1);
        em.persist(ue1);
        // we will add a "ROLE_USER" by default
        List<AuthEntity> ael = new ArrayList<AuthEntity>();
        AuthEntity ae = new AuthEntity();
        ae.setAuthority(RoleEntity.ROLE_USER);
        ae.setUsername(ub.getUsername());
        ae.setUser_id(ue1.getId());
        ael.add(ae);
        ue1.setAuthSet(ael);
        // now merge
        em.merge(ue1);
        // default role merged
        newUb = new UserBean(ue1);
        // we set this clear text just this once so that it can be emailed
        // to user
        newUb.setPassword(newPassword);
        // Add message to be displayed on UI
        ctx.getMessageContext()
                .addMessage(new MessageBuilder().info().defaultText("User added successfuly.").build());
    } else {
        // Add message to be displayed on UI
        ctx.getMessageContext().addMessage(new MessageBuilder().error()
                .defaultText("Username has been taken already. Choose another.").build());
    }
    return newUb;
}

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

public long getUserCount() throws UserManagementException {
    Query query = getNamedQuery("User.count");
    Long count = (Long) query.getSingleResult();
    return count;
}

From source file:cz.muni.fi.pa165.airport.dao.dao.FlightDAO.java

@Override
public boolean isPlaneAvailableForFlight(Long planeId, Flight flight) {
    if (planeId == null) {
        throw new IllegalArgumentException("Plane ID is null");
    }/* www  . j a va2 s .c o m*/
    if (flight == null) {
        throw new IllegalArgumentException("Flight is null");
    }
    if (flight.getDeparture() == null) {
        throw new IllegalArgumentException("Flight departure is null");
    }
    if (flight.getArrival() == null) {
        throw new IllegalArgumentException("Flight arrival is null");
    }
    if (flight.getDeparture().after(flight.getArrival())) {
        throw new IllegalArgumentException("Departure is after arrival");
    }

    Query query = null;
    if (flight.getId() != null) {
        query = em.createNamedQuery(Flight.QUERY_IS_PLANE_AVAILABLE4FLIGHT_EXCLUSIVE);
        query.setParameter("flightId", flight.getId());
    } else {
        query = em.createNamedQuery(Flight.QUERY_IS_PLANE_AVAILABLE4FLIGHT);
    }

    query.setParameter("planeId", planeId);
    query.setParameter("fromT", flight.getDeparture());
    query.setParameter("toT", flight.getArrival());

    Long count = (Long) query.getSingleResult();

    return count == 0;
}

From source file:org.venice.piazza.common.hibernate.dao.deployment.DeploymentDaoImpl.java

public Page<DeploymentEntity> getDeploymentListByDataId(String keyword, Pagination pagination) {
    // Query//from  w  ww.j  a  v  a2s . co  m
    String queryString = String.format(KEYWORD_DATA_ID_QUERY, Direction.fromString(pagination.getOrder()));
    Query query = entityManager.createNativeQuery(queryString, DeploymentEntity.class);
    query.setParameter(1, String.format(WILDCARD_STRING_QUERY, keyword));
    query.setParameter(2, pagination.getSortBy());
    query.setParameter(3, pagination.getPerPage());
    query.setParameter(4, pagination.getPage() * pagination.getPerPage());
    List<DeploymentEntity> results = query.getResultList();
    // Count
    query = entityManager.createNativeQuery(KEYWORD_DATA_ID_QUERY_COUNT);
    query.setParameter(1, String.format(WILDCARD_STRING_QUERY, keyword));
    long count = ((BigInteger) query.getSingleResult()).longValue();
    return new PageImpl<DeploymentEntity>(results, null, count);
}

From source file:eu.trentorise.smartcampus.ac.provider.repository.persistence.AcDaoPersistenceImpl.java

/**
 * Returns the user given its binded authentication token
 * /*from  w  ww.j  av  a2s  .c om*/
 * @param authToken
 *            authentication token binded to the user
 * @return the user or null if no user is binded to the token
 */
@Override
public User readUser(String authToken) {
    try {
        Query query = em.createQuery(
                "from UserEntity u where u.authToken= :authToken or u.sessionAuthToken = :authToken");
        query.setParameter("authToken", authToken);
        try {
            UserEntity ue = (UserEntity) query.getSingleResult();
            User u = PersistenceConverter.toUser(ue);
            if (authToken != null && authToken.equals(ue.getSessionAuthToken())) {
                u.setAuthToken(ue.getSessionAuthToken());
                u.setExpTime(ue.getSessionExpTime());
            }
            return u;
        } catch (NoResultException e) {
            return null;
        }
    } catch (NullPointerException e) {
        return null;
    }
}

From source file:cz.muni.fi.pa165.airport.dao.dao.FlightDAO.java

@Override
public boolean isStewardAvailableForFlight(Long stewardId, Flight flight) {
    if (stewardId == null) {
        throw new IllegalArgumentException("Steward ID is null");
    }/* w  ww .jav  a2s  .  c o m*/
    if (flight == null) {
        throw new IllegalArgumentException("Flight is null");
    }
    if (flight.getDeparture() == null) {
        throw new IllegalArgumentException("Flight departure is null");
    }
    if (flight.getArrival() == null) {
        throw new IllegalArgumentException("Flight arrival is null");
    }
    if (flight.getDeparture().after(flight.getArrival())) {
        throw new IllegalArgumentException("Departure is after arrival");
    }

    Query query = null;
    if (flight.getId() != null) {
        query = em.createNamedQuery(Flight.QUERY_IS_STEWARD_AVAILABLE4FLIGHT_EXCLUSIVE);
        query.setParameter("flightId", flight.getId());
    } else {
        query = em.createNamedQuery(Flight.QUERY_IS_STEWARD_AVAILABLE4FLIGHT);
    }

    query.setParameter("stewardId", stewardId);
    query.setParameter("fromT", flight.getDeparture());
    query.setParameter("toT", flight.getArrival());

    Long count = (Long) query.getSingleResult();

    return count == 0;
}

From source file:cn.hanbell.erp.ejb.PurvdrBean.java

public Purvdr findByVdrno(String vdrno) {
    Query query = getEntityManager().createNamedQuery("Purvdr.findByVdrno");
    query.setParameter("vdrno", vdrno);
    try {/*ww w.  j  a  v a  2 s  .  co  m*/
        return (Purvdr) query.getSingleResult();
    } catch (Exception ex) {
        return null;
    }
}

From source file:cn.hanbell.erp.ejb.PurvdrBean.java

public Purvdr findByVdrds(String vdrds) {
    Query query = getEntityManager().createNamedQuery("Purvdr.findByVdrds");
    query.setParameter("vdrds", vdrds);
    try {//from   ww  w . j  av  a 2  s  .com
        return (Purvdr) query.getSingleResult();
    } catch (Exception ex) {
        return null;
    }
}

From source file:com.openmeap.model.ModelServiceImpl.java

@Override
public int countDeploymentsByHashAndHashAlg(String hash, String hashAlg) {
    Query q = entityManager
            .createQuery("select count(d) " + "from Deployment d " + "left join d.applicationArchive aa "
                    + "where aa.hash=:hash " + "and aa.hashAlgorithm=:hashAlgorithm");
    q.setParameter("hash", hash);
    q.setParameter("hashAlgorithm", hashAlg);
    try {/* w w  w.ja  v a  2s  . c o  m*/
        Number ret = (Number) q.getSingleResult();
        return ret.intValue();
    } catch (NoResultException nre) {
        return 0;
    }
}