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.openmeap.model.ModelServiceImpl.java

@Override
public Application findApplicationByName(String name) {
    Query q = entityManager.createQuery("select distinct a " + "from Application a " + "where a.name=:name");
    q.setParameter("name", name);
    try {/*  w ww.  j  a va2 s .com*/
        return (Application) q.getSingleResult();
    } catch (NoResultException nre) {
        return null;
    }
}

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

/**
 * Get a user from persistence store./*  www . j  ava  2 s .c o m*/
 * @param username
 * @return A single user
 */
public User getUser(String username) {

    User user;

    final Query query = entityManager
            .createQuery("select user from User user " + "left join fetch user.userToRoles utr "
                    + "left join fetch utr.role " + "where user.username= :username ");
    query.setParameter("username", username);
    query.getResultList();

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

    return user;
}

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

@Override
@Transactional(readOnly = true)/* w ww.  j  a v a2 s.c om*/
public String getExpenseStatus(Long expenseId) {
    ExpenseDetail ed = getExpenseById(expenseId);
    if (null == ed.getSettlementId()) {
        return ExpenseEntity.EXPENSE_STATUS_NEW;
    } else {
        Query queryGetSettlementStatus = null;
        queryGetSettlementStatus = em.createNamedQuery("getSettlementStatus");
        queryGetSettlementStatus.setParameter("sid", ed.getSettlementId());
        Integer intResult = (Integer) queryGetSettlementStatus.getSingleResult();
        int r = intResult.intValue();
        if (r == 0) {
            return ExpenseEntity.EXPENSE_STATUS_SETTLEMENT_CREATED;
        } else {
            if (r == 1) {
                return ExpenseEntity.EXPENSE_STATUS_SETTLED;
            } else {
                return "Unknown";
            }
        }
    }
}

From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.test.CommandITCase.java

/**
 * Count meta categories./*  w  ww. j  a  v a2  s .  com*/
 *
 * @return the long
 * @throws Exception the exception
 */
private long countMetaCategories() throws Exception {
    EntityManager em = emf.createEntityManager();
    Query query = em.createQuery("SELECT COUNT(p.fs_id) FROM metaCategory p");
    Long countResult = (Long) query.getSingleResult();

    em.close();

    return countResult;
}

From source file:net.nan21.dnet.core.presenter.service.asgn.AbstractAsgnService.java

/**
 * // w ww .ja  va  2s.  c  o  m
 * @param selectionId
 * @param filter
 * @param params
 * @param builder
 * @return
 * @throws Exception
 */
protected Long count_(String selectionId, F filter, P params, IQueryBuilder<M, F, P> builder) throws Exception {
    QueryBuilderWithJpql<M, F, P> bld = (QueryBuilderWithJpql<M, F, P>) builder;
    Query q = bld.createQueryCount();
    q.setParameter("clientId", Session.user.get().getClient().getId());
    q.setParameter("selectionId", selectionId);
    Object count = q.getSingleResult();
    if (count instanceof Integer) {
        return ((Integer) count).longValue();
    } else {
        return (Long) count;
    }
}

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

public Page<DeploymentEntity> getDeploymentList(Pagination pagination) {
    // Query//from  w w  w  .  j  av  a 2  s .  c  om
    String queryString = String.format(DEPLOYMENT_QUERY, Direction.fromString(pagination.getOrder()));
    Query query = entityManager.createNativeQuery(queryString, DeploymentEntity.class);
    query.setParameter(1, pagination.getSortBy());
    query.setParameter(2, pagination.getPerPage());
    query.setParameter(3, pagination.getPage() * pagination.getPerPage());
    List<DeploymentEntity> results = query.getResultList();
    // Count
    query = entityManager.createNativeQuery(DEPLOYMENT_QUERY_COUNT);
    long count = ((BigInteger) query.getSingleResult()).longValue();
    return new PageImpl<DeploymentEntity>(results, null, count);
}

From source file:com.emc.plants.service.impl.BackOrderStockBean.java

/**
 * Method createBackOrder./*from   w w  w . j  a  v  a 2s .  c  o  m*/
 * @param inventoryID
 * @param amountToOrder
 * @param maximumItems
 */
public void createBackOrder(String inventoryID, int amountToOrder, int maximumItems) {
    try {
        Util.debug("BackOrderStockBean.createBackOrder() - Entered");
        BackOrder backOrder = null;
        try {
            // See if there is already an existing backorder and increase the order quantity
            // but only if it has not been sent to the supplier.
            // backOrder = getBackOrderLocalHome().findByInventoryIDUpdate(inventoryID);
            // TODO: query need updating based on relation?
            Query q = em.createNamedQuery("findByInventoryID");
            q.setParameter("id", inventoryID);
            backOrder = (BackOrder) q.getSingleResult();
            if (!(backOrder.getStatus().equals(Util.STATUS_ORDERSTOCK))) {
                Util.debug(
                        "BackOrderStockBean.createBackOrder() - Backorders found but have already been ordered from the supplier");
                //               throw new FinderException();
            }
            // Increase the BackOrder quantity for an existing Back Order.
            backOrder.setQuantity(backOrder.getQuantity() + amountToOrder);
        } catch (NoResultException e) {
            Util.debug("BackOrderStockBean.createBackOrder() - BackOrder doesn't exist." + e);
            Util.debug("BackOrderStockBean.createBackOrder() - Creating BackOrder for InventoryID: "
                    + inventoryID);
            // Order enough stock from the supplier to reach the maximum threshold and to
            // satisfy the back order.
            amountToOrder = maximumItems + amountToOrder;
            // backOrder = getBackOrderLocalHome().create(inventoryID, amountToOrder);
            Inventory inv = em.find(Inventory.class, inventoryID);
            BackOrder b = new BackOrder(inv, amountToOrder);
            em.persist(b);
        }
    } catch (Exception e) {
        Util.debug("BackOrderStockBean.createBackOrder() - Exception: " + e);
    }
}

From source file:org.venice.piazza.common.hibernate.dao.service.ServiceDaoImpl.java

public Page<ServiceEntity> getServiceList(Pagination pagination) {
    // Query/*from w w w.ja v  a2 s . co m*/
    String queryString = String.format(SERVICE_QUERY, Direction.fromString(pagination.getOrder()));
    Query query = entityManager.createNativeQuery(queryString, ServiceEntity.class);
    query.setParameter(1, pagination.getSortBy());
    query.setParameter(2, pagination.getPerPage());
    query.setParameter(3, pagination.getPage() * pagination.getPerPage());
    List<ServiceEntity> results = query.getResultList();
    // Count
    query = entityManager.createNativeQuery(SERVICE_QUERY_COUNT);
    long count = ((BigInteger) query.getSingleResult()).longValue();
    return new PageImpl<ServiceEntity>(results, null, count);
}

From source file:es.ucm.fdi.dalgs.group.repository.GroupRepository.java

public Group getGroup(Long id_group, Long id_course, Long id_academic) {
    Course course = em.getReference(Course.class, id_course);
    AcademicTerm academic = em.getReference(AcademicTerm.class, id_academic);

    Query query = null;

    query = em.createQuery(//from  w w  w  .java2  s  .co  m
            "select g from Group g where g.course = ?1 and g.id = ?2 and g.course.academicTerm=?3");
    query.setParameter(1, course);
    query.setParameter(2, id_group);
    query.setParameter(3, academic);

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

From source file:gwap.rest.User.java

private JSONObject getUserStatistics(String deviceId, Person person) {
    Query query;
    String username = person.getExternalUsername();

    query = entityManager.createNamedQuery("gameRound.statisticsByPlayer");
    query.setParameter("deviceId", deviceId);
    UserStatistics userStatistics = (UserStatistics) query.getSingleResult();

    query = entityManager.createNamedQuery("gameRound.gamesWonByPlayer");
    query.setParameter("deviceId", deviceId);
    Long gamesWonByPlayer = ((Number) query.getSingleResult()).longValue();

    query = entityManager.createNamedQuery("artResource.byOriginAndDeviceId");
    query.setParameter("origin", ArtResource.ORIGIN_APP_USER);
    query.setParameter("deviceId", deviceId);
    Long photosTaken = ((Number) query.getSingleResult()).longValue();

    query = entityManager.createNamedQuery("artResource.byOriginAndDeviceId");
    query.setParameter("origin", ArtResource.ORIGIN_APP_CRIMESCENE);
    query.setParameter("deviceId", deviceId);
    Long crimescenesTaken = ((Number) query.getSingleResult()).longValue();

    query = entityManager.createNamedQuery("badge.byDeviceId");
    query.setParameter("deviceId", deviceId);
    List<Badge> unlockedBadges = query.getResultList();

    query = entityManager.createNamedQuery("badge.byPlatform");
    query.setParameter("platform", "inspectorXApp");
    List<Badge> allBadges = query.getResultList();

    query = entityManager.createNamedQuery("highscore.all");
    query.setParameter("gametype", getGameType());
    List<Highscore> highscores = query.getResultList();
    int highscoreRank = 0;
    for (int i = 0; i < highscores.size(); i++) {
        if (highscores.get(i).getPersonId().equals(person.getId())) {
            highscoreRank = i + 1;/*from w w w  . ja  va  2 s.co  m*/
            break;
        }
    }

    JSONObject userObject = new JSONObject();
    userObject.put("id", deviceId);
    userObject.put("username", username);
    userObject.put("score", userStatistics.getScore());
    userObject.put("playedTime", userStatistics.getSecondsPlayed());
    userObject.put("gamesPlayed", gamesWonByPlayer);
    userObject.put("photosTaken", photosTaken);
    userObject.put("crimescenesTaken", crimescenesTaken);
    userObject.put("coveredDistance", userStatistics.getCoveredDistance());
    userObject.put("rank", highscoreRank);

    JSONArray badgesArray = new JSONArray();
    for (Badge badge : allBadges) {
        JSONObject jsonBadge = new JSONObject();
        jsonBadge.put("id", badge.getId());
        jsonBadge.put("name", badge.getName());
        jsonBadge.put("description", badge.getDescription());
        jsonBadge.put("worth", badge.getWorth());
        if (unlockedBadges.contains(badge))
            jsonBadge.put("unlocked", true);
        else
            jsonBadge.put("unlocked", false);
        badgesArray.add(jsonBadge);
    }
    userObject.put("badges", badgesArray);
    return userObject;
}