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.telefonica.euro_iaas.paasmanager.dao.impl.SubNetworkDaoJpaImpl.java

private SubNetwork findByNetworkName(String name, String vdc, String region) throws EntityNotFoundException {
    Query query = getEntityManager().createQuery(
            "select p from SubNetwork p where p.name = :name and p.vdc = :vdc and p.region = :region");
    query.setParameter("name", name);
    query.setParameter("vdc", vdc);
    query.setParameter("region", region);
    SubNetwork subNetwork = null;/*from   w  ww.j a  v  a2 s  . co m*/
    try {
        subNetwork = (SubNetwork) query.getSingleResult();
    } catch (NoResultException e) {
        String message = " No subNetwork found in the database with id: " + name + " vdc " + vdc + " region "
                + region + " Exception: " + e.getMessage();
        throw new EntityNotFoundException(SubNetwork.class, "name", name);
    }
    return subNetwork;
}

From source file:es.ucm.fdi.dalgs.subject.repository.SubjectRepository.java

public Subject existByCode(String code) {
    Query query = em.createQuery("Select s from Subject s where s.info.code=?1");
    query.setParameter(1, code);/*from  w w w. j  ava2  s.co  m*/

    if (query.getResultList().isEmpty())
        return null;
    else
        return (Subject) query.getSingleResult();
}

From source file:es.ucm.fdi.dalgs.user.repository.UserRepository.java

public User findByEmail(String email) {
    Query query = em.createQuery("select s from User s where s.email=?1");
    query.setParameter(1, email);/*from  w w  w.  jav  a 2 s  .c o m*/

    if (query.getResultList().isEmpty()) {
        //         logger.error("User not found by email " + email);
        return null;
    }
    return (User) query.getSingleResult();
}

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

@Transactional(propagation = Propagation.SUPPORTS)
protected Object findSingleResult(Query query) throws NotFoundException {
    try {/*from   w w w . j  av a 2 s . co  m*/
        return query.getSingleResult();
    } catch (NoResultException e) {
        throw new NotFoundException("Result of " + query + " with parameters '"
                + Arrays.toString(query.getParameters().toArray()) + "' not found in database", e);
    }
}

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

/**
 * {@inheritDoc}/*from  www .ja v  a  2  s .  c o m*/
 */
public PermissionGrant getPermissionGrant(String id) throws SocialSiteException {
    if (id == null) {
        throw new SocialSiteException("id is null");
    }
    Query query = strategy.getNamedQuery("PermissionGrant.getById");
    query.setParameter(1, id);
    try {
        return (PermissionGrant) query.getSingleResult();
    } catch (NonUniqueResultException ne) {
        throw new SocialSiteException("ERROR: more than one PermissionGrant with id: " + id, ne);
    } catch (NoResultException ex) {
        return null;
    }
}

From source file:utils.jpa.EntityResource.java

public int getAllCount(TableSearchQuery tb, List<String> fieldsSearchBy) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery cq = cb.createQuery();
    Root<T> root = cq.from(entityClass);
    cq.select(cb.count(root));//from w  ww  . j  a  v a 2 s.c om
    Query query = tb.createQuery(em, cb, cq, root);
    if (query == null) {
        query = createCommonQuery(cb, cq, root, tb, fieldsSearchBy);
    }
    try {
        return ((Long) query.getSingleResult()).intValue();
    } catch (NoResultException ex) {
        return 0;
    }
}

From source file:gwap.rest.User.java

@PUT
@Consumes(MediaType.APPLICATION_JSON)/*w ww .  j  a v a2s  .c  om*/
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
@Transactional
@Path("/{id:[A-Za-z0-9][A-Za-z0-9]*}")
public Response updateUser(@PathParam("id") String deviceId, String payloadString) {
    log.info("updateUser(#0)", deviceId);
    JSONObject payload = parse(payloadString);
    Query query = entityManager.createNamedQuery("person.byDeviceId");
    query.setParameter("deviceId", deviceId);
    Person person = (Person) query.getSingleResult();

    if (payload.containsKey("username")) { // update user
        person.setExternalUsername(payload.get("username").toString());
    } else { // create new gamesession+gameround
        query = entityManager.createNamedQuery("gameSession.byGameType");
        query.setParameter("gameType", getGameType());
        GameSession gameSession;
        try {
            gameSession = (GameSession) query.getSingleResult();
        } catch (NoResultException e) {
            gameSession = new GameSession();
            gameSession.setGameType(getGameType());
            entityManager.persist(gameSession);
        }

        int score = Integer.parseInt(payload.get("score").toString());
        int playedTime = Integer.parseInt(payload.get("playedTime").toString());
        double coveredDistance = Double.parseDouble(payload.get("coveredDistance").toString());
        boolean successful = Integer.parseInt(payload.get("gamesPlayed").toString()) == 1;

        GameRound gameRound = new GameRound();
        entityManager.persist(gameRound);
        gameRound.setGameSession(gameSession);
        gameRound.setPerson(person);
        gameRound.setScore(score);
        Calendar cal = GregorianCalendar.getInstance();
        gameRound.setEndDate(cal.getTime());
        cal.add(Calendar.MILLISECOND, -1 * playedTime);
        gameRound.setStartDate(cal.getTime());
        gameRound.setCoveredDistance(coveredDistance);
        gameRound.setSuccessful(successful);

        // Unlock new badges
        JSONArray newBadges = (JSONArray) payload.get("badges");
        for (Object o : newBadges) {
            JSONObject badge = (JSONObject) o;
            long badgeId = Long.parseLong(badge.get("id").toString());
            if (Boolean.parseBoolean(badge.get("unlocked").toString())) {
                Badge b = entityManager.find(Badge.class, badgeId);
                person.getBadges().add(b);
            }
        }

    }
    entityManager.flush();
    log.info("Sucessfully updated user with deviceId #0", deviceId);
    return Response.ok().build();
}

From source file:es.ucm.fdi.dalgs.user.repository.UserRepository.java

public User findByUsername(String username) {
    Query query = em.createQuery("select s from User s where s.username=?1");
    query.setParameter(1, username);/*from w  ww .  j  a  va2s.co m*/

    if (query.getResultList().isEmpty()) {
        logger.error("User not found by username " + username);
        return null;
    }

    return (User) query.getSingleResult();
}

From source file:de.voolk.marbles.persistence.services.PageService.java

@Override
public IPage findPageByUserAndParentAndName(IUser user, IPage parent, String name) {
    Query query = getEntityManager().createNamedQuery("page:byUserAndParentAndName");
    query.setParameter("user", user);
    query.setParameter("parent", resolve(Page.class, parent));
    query.setParameter("name", name);
    try {/*w  w  w .  j  a v  a  2  s .c  om*/
        return (Page) query.getSingleResult();
    } catch (NoResultException e) {
        return null;
    }
}

From source file:org.jrecruiter.dao.jpa.UserDaoJpa.java

/** {@inheritDoc} */
public User getUserByVerificationKey(final String key) {

    User user;//  w w  w  . j a  va 2  s.  co m

    final Query query = entityManager
            .createQuery("select user from User user " + "where user.verificationKey = :key ");
    query.setParameter("key", key);
    query.getResultList();

    try {
        user = (User) query.getSingleResult();
    } catch (NoResultException e) {
        user = null;
    }

    return user;
}