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.soulwing.credo.repository.JpaUserGroupMemberRepository.java

/**
 * {@inheritDoc}/*from   w  ww.j  av a2  s .com*/
 */
@Override
public UserGroupMember findByGroupNameAndLoginName(String groupName, String loginName) {

    if (UserGroup.SELF_GROUP_NAME.equals(groupName)) {
        groupName = null;
    }

    String queryName = groupName != null ? "findGroupMemberWithGroupNameAndLoginName" : "findGroupMemberSelf";
    TypedQuery<UserGroupMember> query = entityManager.createNamedQuery(queryName, UserGroupMember.class);

    if (groupName != null) {
        query.setParameter("groupName", groupName);
    }
    query.setParameter("loginName", loginName);

    try {
        return query.getSingleResult();
    } catch (NoResultException ex) {
        return null;
    }
}

From source file:org.springframework.data.jpa.repository.support.SimpleJpaRepository.java

public boolean exists(ID id) {

    Assert.notNull(id, "The given id must not be null!");

    if (entityInformation.getIdAttribute() == null) {
        return findOne(id) != null;
    }//  w  w  w.  ja  v  a2  s  .  c  o m

    String placeholder = provider.getCountQueryPlaceholder();
    String entityName = entityInformation.getEntityName();
    Iterable<String> idAttributeNames = entityInformation.getIdAttributeNames();
    String existsQuery = QueryUtils.getExistsQueryString(entityName, placeholder, idAttributeNames);

    TypedQuery<Long> query = em.createQuery(existsQuery, Long.class);

    if (!entityInformation.hasCompositeId()) {
        query.setParameter(idAttributeNames.iterator().next(), id);
        return query.getSingleResult() == 1L;
    }

    for (String idAttributeName : idAttributeNames) {

        Object idAttributeValue = entityInformation.getCompositeIdAttributeValue(id, idAttributeName);

        boolean complexIdParameterValueDiscovered = idAttributeValue != null && !query
                .getParameter(idAttributeName).getParameterType().isAssignableFrom(idAttributeValue.getClass());

        if (complexIdParameterValueDiscovered) {

            // fall-back to findOne(id) which does the proper mapping for the parameter.
            return findOne(id) != null;
        }

        query.setParameter(idAttributeName, idAttributeValue);
    }

    return query.getSingleResult() == 1L;
}

From source file:otn.mobile.bl.TrackServicesHandler.java

public OtnServiceTrackVerificationResponse addVerification(OtnServiceTrackVerificationRequest request) {
    OtnServiceTrackVerificationResponse response = new OtnServiceTrackVerificationResponse();

    Track track;// www  .  ja  v a 2  s  .  com

    TypedQuery query;

    User users;

    Apps app = null;

    TrackVerified trackVerified;

    try {

        users = em.find(User.class, request.getUserId());

        if (users == null) {
            response.setMessage("user does not exist");
            response.setResponseCode(1);
            return response;
        }

        //find track
        em.getTransaction().begin();

        //add verification to  track
        //***********************find app name******************************
        if (request.getAppId() != 0) {
            app = em.find(Apps.class, request.getAppId());
            if (app == null) {
                response.setMessage("application does not exist");
                response.setResponseCode(1);
                return response;
            }
        }

        query = (TypedQuery) em
                .createQuery("SELECT t FROM Track t WHERE t.appId = :appId and t.trackId = :trackId ");

        query.setParameter("appId", app);
        query.setParameter("trackId", request.getTrackId());

        if (query.getResultList().isEmpty()) {
            response.setMessage("track id does not exist for this app");
            response.setResponseCode(1);
            return response;
        } else {
            track = (Track) query.getSingleResult();

        }

        query = (TypedQuery) em.createQuery(
                "SELECT t FROM Track t WHERE t.appId = :appId and t.trackId = :trackId and t.userId != :userId");

        query.setParameter("appId", app);
        query.setParameter("trackId", request.getTrackId());
        query.setParameter("userId", users);

        if (query.getResultList().isEmpty()) {
            response.setResponseCode(501);
            response.setMessage("the owner of the track cannot verify the track");
            if (track.getVerified() != null) {
                response.setVerification(track.getVerified());
            }
            return response;
        } else {
            track = (Track) query.getSingleResult();
        }

        query = (TypedQuery) em
                .createQuery("SELECT t FROM TrackVerified t WHERE t.userId = :userId and t.trackId = :trackId");

        query.setParameter("userId", users);
        query.setParameter("trackId", track);

        if (query.getResultList().isEmpty()) {
            if (track.getVerified() == null) {
                track.setVerified(0);
            }
            track.setVerified(track.getVerified() + 1);
            em.merge(track);

            /**
             * create new record to poi verified so this user cannot verify
             * again the POI
             */
            response.setVerification(track.getVerified());
            response.setTrackId(track.getTrackId());

            trackVerified = new TrackVerified();
            trackVerified.setTrackId(track);
            trackVerified.setUserId(users);

            em.persist(trackVerified);
            em.flush();
            em.getTransaction().commit();

            response.setMessage("success");
            response.setResponseCode(0);
        } else {
            response.setMessage("Route is already verified");
            response.setResponseCode(501);
            response.setVerification(track.getVerified());
            response.setTrackId(track.getTrackId());

        }

        return response;
    } catch (Exception e) {
        e.printStackTrace();
        response.setMessage("failure");
        response.setResponseCode(2);
        return response;
    } finally {
        em.clear();
    }

}

From source file:pl.datamatica.traccar.api.providers.UserProvider.java

public User getUserByLogin(String login) {
    try {//from w  w  w.  j  a  v  a  2  s  .  com
        TypedQuery<User> tq = em.createQuery("Select x from User x where x.login = :login", User.class);
        tq.setParameter("login", login);
        return tq.getSingleResult();
    } catch (NoResultException e) {
        return null;
    }
}

From source file:pl.datamatica.traccar.api.providers.UserProvider.java

private User getUserByToken(String tokenType, String token) {
    try {//from   w  w w .ja  v a 2 s  .  co  m
        TypedQuery<User> tq = em.createQuery("Select x from User x " + "where x." + tokenType + " = :token",
                User.class);
        tq.setParameter("token", token);
        return tq.getSingleResult();
    } catch (NoResultException e) {
        return null;
    }
}

From source file:ru.codeinside.adm.AdminServiceImpl.java

private int selectGroupsBySocialCount(AdvancedFilterableSupport newSender, boolean social) {
    StringBuilder q = new StringBuilder("SELECT count(g) FROM Group g where g.social = :social");

    if (newSender != null) {
        for (Container.Filter f : newSender.getFilters()) {
            String field = ((SimpleStringFilter) f).getPropertyId().toString();
            q.append(" and lower(g.").append(field).append(") LIKE lower(:").append(field).append(")");
        }// ww  w .j a  v  a  2 s . c om
    }

    TypedQuery<Long> query = em.createQuery(q.toString(), Long.class).setParameter("social", social);
    if (newSender != null) {
        for (Container.Filter f : newSender.getFilters()) {
            String field = ((SimpleStringFilter) f).getPropertyId().toString();
            String value = ((SimpleStringFilter) f).getFilterString();
            query.setParameter(field, "%" + value + "%");
        }
    }
    return query.getSingleResult().intValue();
}

From source file:ru.codeinside.adm.AdminServiceImpl.java

private int getControlledGroupsCount(Employee employee, AdvancedFilterableSupport newSender, String target) {
    StringBuilder q = new StringBuilder("select count(e." + target + ") from Employee e where e = :employee");

    if (newSender != null) {
        for (Container.Filter f : newSender.getFilters()) {
            String field = ((SimpleStringFilter) f).getPropertyId().toString();
            q.append(" and lower(e.").append(target).append(".").append(field).append(") LIKE lower(:")
                    .append(field).append(")");
        }//from www .  j  a  v  a  2 s. com
    }

    TypedQuery<Long> query = em.createQuery(q.toString(), Long.class).setParameter("employee", employee);
    if (newSender != null) {
        for (Container.Filter f : newSender.getFilters()) {
            String field = ((SimpleStringFilter) f).getPropertyId().toString();
            String value = ((SimpleStringFilter) f).getFilterString();
            query.setParameter(field, "%" + value + "%");
        }
    }
    return query.getSingleResult().intValue();
}

From source file:ru.codeinside.adm.AdminServiceImpl.java

public int countOfBidByEmail(String login, AdvancedFilterableSupport newSender) {
    StringBuilder q = new StringBuilder(
            "select count(distinct s.bid.id) from BidWorkers s where s.employee.login=:login ");

    Set<Timestamp> timestamps = null;
    if (newSender != null) {
        timestamps = archiveQueryFilters(newSender, q);
    }/*from  w ww .j av a 2 s .c om*/
    TypedQuery<Number> query = em.createQuery(q.toString(), Number.class).setParameter("login", login);
    if (newSender != null) {
        for (Container.Filter filter : newSender.getFilters()) {
            if (filter instanceof SimpleStringFilter) {
                String field = ((SimpleStringFilter) filter).getPropertyId().toString();
                String value = ((SimpleStringFilter) filter).getFilterString();
                if (field.equals("procedure.name")) {
                    query.setParameter("name", "%" + value + "%");
                } else if (field.equals("id")) {
                    try {
                        query.setParameter(field, Long.parseLong(value));
                    } catch (Exception e) {
                        //
                    }
                }
            }
        }
        Iterator<Timestamp> iterator = timestamps.iterator();
        if (timestamps.size() == 1) {
            return query.setParameter("value", iterator.next()).getSingleResult().intValue();
        } else if (timestamps.size() == 2) {
            Timestamp next = iterator.next();
            Timestamp next1 = iterator.next();
            return query.setParameter("startValue", next).setParameter("endValue", next1).getSingleResult()
                    .intValue();
        }
    }

    return query.getSingleResult().intValue();
}

From source file:se.nrm.dina.data.jpa.impl.DinaDaoImpl.java

@Override
public Object[] getListOfDataByJPQL(String jpql) {
    logger.info("getListOfDataByJPQL : {}", jpql);

    TypedQuery<Object[]> typedQuery = entityManager.createQuery(jpql, Object[].class);
    try {// www . j  a  v  a2  s  . c om
        return typedQuery.getSingleResult();
    } catch (NoResultException | NonUniqueResultException ex) {
        logger.info(ex.getMessage() + " ... " + jpql);
    }
    return null;
}

From source file:uk.ac.edukapp.service.WidgetProfileService.java

public Widgetprofile findWidgetProfileByName(String name) {
    Widgetprofile wp = null;/*from   ww w .  j a v  a 2  s.c  om*/
    EntityManager entityManager = this.getEntityManagerFactory().createEntityManager();
    try {
        String sql = "SELECT w FROM Widgetprofile w WHERE w.name = :widgetName";
        TypedQuery<Widgetprofile> query = entityManager.createQuery(sql, Widgetprofile.class);
        query.setParameter("widgetName", name);
        wp = query.getSingleResult();
    } catch (NoResultException exception) {
        // fine don't do anything
    }
    entityManager.close();
    return wp;
}