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.openmeetings.app.data.user.dao.UsersDaoImpl.java

public Users getUserByEmail(String email) {
    try {/*from   www. j  a va2 s. c o m*/
        String hql = "SELECT u FROM Users as u " + " where u.adresses.email = :email"
                + " AND u.deleted <> :deleted";
        TypedQuery<Users> query = em.createQuery(hql, Users.class);
        query.setParameter("email", email);
        query.setParameter("deleted", "true");
        Users us = null;
        try {
            us = query.getSingleResult();
        } catch (NoResultException ex) {
        }
        return us;
    } catch (Exception e) {
        log.error("[getUserByAdressesId]", e);
    }
    return null;
}

From source file:org.cleverbus.core.common.dao.MessageDaoJpaImpl.java

@Override
public int getCountMessages(MsgStateEnum state, Integer interval) {
    Date lastUpdateTime = null;//from w w w .ja  v  a  2 s  .  c o  m

    String jSql = "SELECT COUNT(m) " + "FROM " + Message.class.getName() + " m " + "WHERE m.state = '"
            + state.name() + "'";

    if (interval != null) {
        lastUpdateTime = DateUtils.addSeconds(new Date(), -interval);
        jSql += " AND m.lastUpdateTimestamp >= :lastUpdateTime";
    }

    TypedQuery<Number> q = em.createQuery(jSql, Number.class);
    if (lastUpdateTime != null) {
        q.setParameter("lastUpdateTime", new Timestamp(lastUpdateTime.getTime()));
    }

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

From source file:io.github.davejoyce.dao.composite.social.connect.jpa.JpaConnectionRepository.java

/**
 * {@inheritDoc}//from w ww.ja  va2 s .  co  m
 */
@Transactional
public void addConnection(Connection<?> connection) {
    try {
        ConnectionData cd = connection.createData();
        // Get next rank, default to 1
        TypedQuery<Integer> nextRankQuery = entityManager.createQuery(QUERY_NEXT_RANK, Integer.class)
                .setParameter("userId", userId).setParameter("providerId", cd.getProviderId());
        Integer nextRank = nextRankQuery.getSingleResult();
        // Build & persist new AppUserSocialConnection object
        AppUser appUser = entityManager.find(AppUser.class, userId);
        AppUserSocialConnection ausc = new AppUserSocialConnection();
        ausc.setKey(new AppUserSocialConnectionKey(appUser, cd.getProviderId(), cd.getProviderUserId()));
        ausc.setRank(nextRank.intValue());
        ausc.setDisplayName(cd.getDisplayName());
        ausc.setProfileUrl(cd.getProfileUrl());
        ausc.setImageUrl(cd.getImageUrl());
        ausc.setAccessToken(encrypt(cd.getAccessToken()));
        ausc.setSecret(encrypt(cd.getSecret()));
        ausc.setRefreshToken(encrypt(cd.getRefreshToken()));
        ausc.setExpireTime(cd.getExpireTime());
        entityManager.persist(ausc);
    } catch (EntityExistsException eee) {
        throw new DuplicateConnectionException(connection.getKey());
    }
}

From source file:ru.portal.services.TableServiceImpl.java

/**
 * TODO    ManyToMany/* w w w. j av  a2  s  . c o  m*/
 * @param entityClass
 * @param id
 * @return 
 */
@Override
public Map<EntityType<?>, Map<String, String>> findByEntityClassId(String entityClass, String id) {

    try {
        Class<?> cl = Class.forName(entityClass);
        EntityType<?> entityType = em.getEntityManagerFactory().getMetamodel().entity(cl);
        if (entityType != null && entityType.getBindableJavaType().getAnnotation(PortalTable.class) != null) {
            if (entityType.getBindableJavaType().getName().equals(entityClass)) {
                Class<?> bindableJavaType = entityType.getBindableJavaType();
                //select

                CriteriaBuilder cb = em.getCriteriaBuilder();
                CriteriaQuery<?> cq = cb.createQuery(bindableJavaType);
                Root<?> root = cq.from(User.class);

                cq.where(cb.equal(root.get("id"), Long.parseLong(id)));

                TypedQuery<?> query = em.createQuery(cq);
                ParameterExpression<Long> parameter = cb.parameter(Long.class, "id");
                //query.setParameter(parameter, Long.parseLong(id));
                //query.unwrap(org.hibernate.Query.class).getQueryString();

                Object result = query.getSingleResult();

                List<String> columns = getTableOrViewMetaData(entityClass);

                HashMap<String, String> res = new HashMap<>(columns.size());
                Class<? extends Object> clazz = result.getClass();
                for (String fieldName : columns) {
                    try {
                        Field field = clazz.getDeclaredField(fieldName);
                        field.setAccessible(true);
                        Object fieldValue = field.get(result);
                        res.put(fieldName, fieldValue.toString());
                    } catch (NoSuchFieldException | SecurityException | IllegalArgumentException
                            | IllegalAccessException ex) {
                        Logger.getLogger(TableServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

                System.out.println(res);
                Map<EntityType<?>, Map<String, String>> hm = new HashMap<>();
                hm.put(entityType, res);
                return hm;

            }
        }

    } catch (ClassNotFoundException ex) {
        Logger.getLogger(TableServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:com.softwarecorporativo.monitoriaifpe.funcionais.atividade.TesteAtividade.java

@Test
public void testeConsultarAtividadeMaisAntiga() {
    Atividade atividadeEsperada = super.entityManager.find(Atividade.class, 1L);
    TypedQuery<Atividade> query = super.entityManager.createQuery(
            "SELECT a FROM Atividade a WHERE NOT(a.data > ALL ( SELECT aa.data FROM Atividade aa))",
            Atividade.class);

    Atividade atividade = query.getSingleResult();
    assertEquals(atividadeEsperada, atividade);
}

From source file:com.github.fharms.camel.route.CamelEntityManagerTestRouteTest.java

private Dog findDogByPetName(String petname) {
    TypedQuery<Dog> typedQuery = em.createQuery("select d from Dog d where d.petName = :petname", Dog.class);
    typedQuery.setParameter("petname", petname);
    Dog result = null;/*from   w w w . j a v a 2s  . c  o m*/
    try {
        result = typedQuery.getSingleResult();
    } catch (Exception e) {
        result = null;
    }
    return result;
}

From source file:org.openmeetings.app.data.calendar.daos.MeetingMemberDaoImpl.java

public MeetingMember getMeetingMemberById(Long meetingMemberId) {
    try {//from w  w  w . j a v a 2s  .c om
        log.debug("getMeetingMemberById: " + meetingMemberId);

        String hql = "select app from MeetingMember app " + "WHERE app.deleted <> :deleted "
                + "AND app.meetingMemberId = :meetingMemberId";

        TypedQuery<MeetingMember> query = em.createQuery(hql, MeetingMember.class);
        query.setParameter("deleted", true);
        query.setParameter("meetingMemberId", meetingMemberId);

        MeetingMember meetingMember = null;
        try {
            meetingMember = query.getSingleResult();
        } catch (NoResultException ex) {
        }

        return meetingMember;
    } catch (Exception ex2) {
        log.error("[getMeetingMemberById]: ", ex2);
    }
    return null;
}

From source file:org.openmeetings.app.data.user.dao.UsersDaoImpl.java

public Object getUserByHash(String hash) {
    try {//  www . j  a  v a 2  s  .c  o  m
        if (hash.length() == 0)
            return new Long(-5);
        String hql = "SELECT u FROM Users as u " + " where u.resethash = :resethash"
                + " AND u.deleted <> :deleted";
        TypedQuery<Users> query = em.createQuery(hql, Users.class);
        query.setParameter("resethash", hash);
        query.setParameter("deleted", "true");
        Users us = null;
        try {
            us = query.getSingleResult();
        } catch (NoResultException ex) {
        }
        if (us != null) {
            return us;
        } else {
            return new Long(-5);
        }
    } catch (Exception e) {
        log.error("[getUserByAdressesId]", e);
    }
    return new Long(-1);
}

From source file:com.epam.training.taranovski.web.project.repository.implementation.OfferBidRepositoryImplementation.java

@Override
public OfferBid getBidByEmployeeAndVacancy(Employee employee, Vacancy vacancy) {
    EntityManager em = entityManagerFactory.createEntityManager();
    OfferBid offer = null;/*from  w  ww.  j a v a  2s .  c  om*/
    try {
        em.getTransaction().begin();

        TypedQuery<OfferBid> query = em.createNamedQuery("OfferBid.findBidByEmployeeAndVacancy",
                OfferBid.class);
        query.setParameter("employee", employee);
        query.setParameter("vacancy", vacancy);
        offer = query.getSingleResult();

        em.getTransaction().commit();
    } catch (RuntimeException e) {
        Logger.getLogger(OfferBidRepositoryImplementation.class.getName()).info(e);
        offer = null;
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        em.close();
    }

    return offer;
}

From source file:com.epam.training.taranovski.web.project.repository.implementation.OfferBidRepositoryImplementation.java

@Override
public OfferBid getOfferByEmployeeAndVacancy(Employee employee, Vacancy vacancy) {
    EntityManager em = entityManagerFactory.createEntityManager();
    OfferBid offer = null;//ww w. jav a 2  s . co  m
    try {
        em.getTransaction().begin();

        TypedQuery<OfferBid> query = em.createNamedQuery("OfferBid.findOfferByEmployeeAndVacancy",
                OfferBid.class);
        query.setParameter("employee", employee);
        query.setParameter("vacancy", vacancy);
        offer = query.getSingleResult();

        em.getTransaction().commit();
    } catch (RuntimeException e) {
        Logger.getLogger(OfferBidRepositoryImplementation.class.getName()).info(e);
        offer = null;
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        em.close();
    }

    return offer;
}