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.espirit.moddev.examples.uxbridge.newsdrilldown.test.NewsITCase.java

/**
 * Test persistence./*from   ww  w . j  a  v a2s.c o  m*/
 *
 * @throws Exception the exception
 */
@Test
public void testPersistence() throws Exception {

    long size = countNews();

    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = null;
    try {
        tx = em.getTransaction();
        tx.begin();

        News news = new News();

        news.setContent("Spider-man was seen.");
        news.setHeadline("The amazing spider-man");
        news.setFs_id(1l);
        news.setLanguage("DE");
        news.setTeaser("spider-man");

        NewsCategory sport = new NewsCategory();
        sport.setFs_id(2l);
        sport.setName("Sport");
        sport.setLanguage("DE");

        NewsMetaCategory soccer = new NewsMetaCategory();
        soccer.setFs_id(3l);
        soccer.setLanguage("DE");
        soccer.setName("Fussball");

        if (sport.getMetaCategories() == null) {
            sport.setMetaCategories(new ArrayList<NewsMetaCategory>());
        }
        sport.getMetaCategories().add(soccer);

        if (news.getCategories() == null) {
            news.setCategories(new ArrayList<NewsCategory>());
        }
        news.getCategories().add(sport);

        em.persist(news);
        em.flush();
        tx.commit();

        assertEquals("Entity not filled", size + 1, countNews());

        Query query = em.createQuery("SELECT mc FROM metaCategory mc WHERE fs_id=3");
        NewsMetaCategory metaCat = (NewsMetaCategory) query.getSingleResult();
        assertNotNull(metaCat);

        query = em.createQuery(
                "SELECT c FROM category c join c.metaCategories mc WHERE mc.fs_id=" + metaCat.getFs_id());
        NewsCategory category = (NewsCategory) query.getSingleResult();
        assertNotNull(category);

        query = em.createQuery("SELECT n FROM news n join n.categories c WHERE c.fs_id=" + category.getFs_id());
        News n = (News) query.getSingleResult();
        assertNotNull(n);

    } finally {
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }

}

From source file:com.healthcit.cacure.dao.FormDao.java

public Long getNumberOfFormsForModuleId(Long moduleId) {
    String q = "select count(distinct frm) from QuestionnaireForm frm " + "where frm.module.id = :moduleId";
    Query query = em.createQuery(q);
    query.setParameter("moduleId", moduleId);
    return (Long) query.getSingleResult();
}

From source file:com.taobao.ad.easyschedule.base.JPABaseDAO.java

public int getQueryCount(String queryString, final Map<String, Object> map) {
    final List<String> keyList = getKeyList(map);
    final String queryStringCallBack = getQueryString(queryString, keyList, null);
    return (Integer) this.getJpaTemplate().execute(new JpaCallback() {

        @Override//from  w w w. j av a 2 s .  c  o  m
        public Integer doInJpa(EntityManager em) throws PersistenceException {
            Query query = em.createQuery(queryStringCallBack);
            for (int i = 0; i < keyList.size(); i++) {
                query.setParameter((i + 1), map.get(keyList.get(i)));
            }
            return ((Long) query.getSingleResult()).intValue();
        }
    });
}

From source file:gwap.rest.UserPicture.java

protected void persistPicturerating(String idString, String payloadString) {
    JSONObject jsonObject = parse(payloadString);

    Query query = entityManager.createNamedQuery("person.byDeviceId");
    query.setParameter("deviceId", jsonObject.get("userid").toString());
    Person person = (Person) query.getSingleResult();

    ArtResourceRating artResourceRating = new ArtResourceRating();
    artResourceRating.setPerson(person);

    if (jsonObject.containsKey("likes"))
        artResourceRating.setRating(1L);
    else/*from   w  w  w  . j av  a 2s  .  c  om*/
        artResourceRating.setRating(-1L);

    entityManager.persist(artResourceRating);
    ArtResource artResource = entityManager.find(ArtResource.class, Long.parseLong(idString));
    artResource.getRatings().add(artResourceRating);
    artResourceRating.setResource(artResource);
    entityManager.flush();
    log.info("Added ArtResourceRating #0", artResourceRating.getId());

    log.info("Updated UserPicture #0", artResource.getId());
}

From source file:it.scoppelletti.programmerpower.security.DefaultUserManager.java

/**
 * Legge un utente./*from w  w w  . j a  va  2s  .c o  m*/
 * 
 * @param  userName Codice per l&rsquo;autenticazione dell&rsquo;utente.
 * @return          Utente. Non pu&ograve; essere {@code null}.
 */
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String userName) {
    Query query;

    if (Strings.isNullOrEmpty(userName)) {
        throw new ArgumentNullException("userName");
    }

    query = myEntityMgr.createQuery("from User where code = :code").setParameter("code", userName);

    return (User) query.getSingleResult();
}

From source file:org.apache.cxf.fediz.service.idp.service.jpa.EntitlementDAOJPAImpl.java

@Override
public void updateEntitlement(String name, Entitlement entitlement) {
    Query query = null;
    query = em.createQuery("select e from Entitlement e where e.name=:name");
    query.setParameter("name", name);

    //@SuppressWarnings("rawtypes")
    EntitlementEntity entitlementEntity = (EntitlementEntity) query.getSingleResult();

    domain2entity(entitlement, entitlementEntity);

    LOG.debug("Entitlement '{}' added", entitlement.getName());
    em.persist(entitlementEntity);/*from w ww.j a va2s  .co m*/
}

From source file:Professor.java

  public Professor findProfessorNoCache(int empId) {
  Query q = em.createQuery("SELECT e FROM Professor e WHERE e.id = ?1");
  // force read from database
  q.setHint("cacheUsage", oracle.toplink.essentials.queryframework.ObjectLevelReadQuery.DoNotCheckCache);
  q.setParameter(1, empId);/*w  w w . j  ava2s .  c  om*/
  try {
    return (Professor) q.getSingleResult();
  } catch (NoResultException e) {
    return null;
  }
}

From source file:org.kuali.mobility.push.dao.SenderDaoImpl.java

public boolean isValidSenderKey(String senderKey) {
    Query query = entityManager.createQuery("select s from Sender s where s.senderKey = :senderKey");
    query.setParameter("senderKey", senderKey);
    try {/*from w w w .  ja  v  a 2 s  .  com*/
        query.getSingleResult();
    } catch (Exception e) {
        LOG.info("SenderKey " + senderKey + " was not found or was invalid.");
        return false;
    }
    return true;
}

From source file:br.ufrgs.inf.dsmoura.repository.model.dao.TypesDAO.java

public SystemPropertyDTO getSystemProperty(String key) {
    Query query = createEntityManager().createNamedQuery("SystemPropertyDTO.getByKey");
    query.setParameter("key", key);
    return (SystemPropertyDTO) query.getSingleResult();
}

From source file:org.kuali.mobility.push.dao.SenderDaoImpl.java

public Sender findSenderById(long id) {
    Query query = entityManager.createQuery("select s from Sender s where s.id = :id");
    query.setParameter("id", id);
    Sender s;/*from   w w  w . j  a va 2  s  .  c om*/
    try {
        s = (Sender) query.getSingleResult();
    } catch (NoResultException e) {
        LOG.info("Sender with id " + id + " was not found or was invalid.");
        return null;
    }
    return s;
}