Example usage for javax.persistence TypedQuery getResultList

List of usage examples for javax.persistence TypedQuery getResultList

Introduction

In this page you can find the example usage for javax.persistence TypedQuery getResultList.

Prototype

List<X> getResultList();

Source Link

Document

Execute a SELECT query and return the query results as a typed List.

Usage

From source file:bq.jpa.demo.query.criteria.service.CriteriaService.java

/**
 * fetch join://  w w  w  .  j  av  a  2 s . c om
 * SELECT e FROM jpa_query_employee e JOIN FETCH e.address
 */
//   @Transactional
public void doFrom3() {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Employee> c = cb.createQuery(Employee.class);
    Root<Employee> e = c.from(Employee.class);
    e.fetch("address");
    e.fetch("department");
    e.fetch("projects", JoinType.INNER);
    //      e.fetch("phones");
    //      e.fetch("directs");
    //      e.fetch("manager");
    c.select(e);

    // only show the fetched data
    TypedQuery<Employee> query = em.createQuery(c);
    List<Employee> result = query.getResultList();
    for (Employee emp : result) {
        System.out.println(emp.getId() + " | " + emp.getName() + " | " + emp.getAddress() + " | "
                + emp.getDepartment() + " | " + emp.getProjects());
    }
}

From source file:org.jasig.portlet.blackboardvcportlet.dao.impl.ConferenceUserDaoImpl.java

@Override
public Set<ConferenceUser> getUsersByAnyEmail(String email) {
    final TypedQuery<ConferenceUserImpl> query = this.createQuery(this.getUsersByAnyEmailQuery);
    query.setParameter(this.emailParameter, email.toUpperCase());

    final List<ConferenceUserImpl> resultList = query.getResultList();
    return new LinkedHashSet<ConferenceUser>(resultList);
}

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

@Override
public Page<HashMap<String, String>> findAll(String tableOrViewName, Pageable pageable) {

    List<HashMap<String, String>> result = new ArrayList<>();

    EntityType<?> type = null;/* w w  w  . j a v  a  2  s  .com*/
    Set<EntityType<?>> set = em.getEntityManagerFactory().getMetamodel().getEntities();
    for (EntityType<?> entityType : set) {
        if (entityType.getBindableJavaType().getAnnotation(PortalTable.class) != null) {
            if (entityType.getBindableJavaType().getName().equals(tableOrViewName)) {
                type = entityType;
                break;
            }
        }
    }

    Long totalRows = 0L;

    if (type != null) {
        Class<?> bindableJavaType = type.getBindableJavaType();

        //count
        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
        CriteriaQuery<Long> countQuery = criteriaBuilder.createQuery(Long.class);
        countQuery.select(criteriaBuilder.count(countQuery.from(bindableJavaType)));
        totalRows = em.createQuery(countQuery).getSingleResult();

        //select
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<?> cq = cb.createQuery(bindableJavaType);
        Root<?> root = cq.from(bindableJavaType);
        //          cq.select(root);
        if (pageable == null) {
            pageable = new PageRequest(0, 50);
        }

        TypedQuery<?> query = em.createQuery(cq);

        query.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
        query.setMaxResults(pageable.getPageSize());
        List<?> all = query.getResultList();

        List<String> columns = getTableOrViewMetaData(tableOrViewName);

        for (Object object : all) {

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

    PageImpl<HashMap<String, String>> list = new PageImpl<>(result, pageable, totalRows);
    return list;
}

From source file:org.mitre.oauth2.repository.impl.JpaOAuth2TokenRepository.java

@Override
public Set<OAuth2RefreshTokenEntity> getAllRefreshTokens() {
    TypedQuery<OAuth2RefreshTokenEntity> query = manager.createNamedQuery(OAuth2RefreshTokenEntity.QUERY_ALL,
            OAuth2RefreshTokenEntity.class);
    return new LinkedHashSet<>(query.getResultList());
}

From source file:org.openmeetings.app.data.logs.ConferenceLogTypeDaoImpl.java

public ConferenceLogType getConferenceLogTypeByEventName(String eventType) {
    try {// w  w w. j  a v a  2 s  .  c  o  m

        String hql = "select a from ConferenceLogType a " + "WHERE a.eventType = :eventType ";

        TypedQuery<ConferenceLogType> query = em.createQuery(hql, ConferenceLogType.class);
        query.setParameter("eventType", eventType);

        //Seems like this does throw an error sometimes cause it does not return a unique Result
        //ConferenceLogType confLogType = (ConferenceLogType) query.getSingleResult();
        List<ConferenceLogType> confLogTypes = query.getResultList();
        ConferenceLogType confLogType = null;
        if (confLogTypes != null && confLogTypes.size() > 0) {
            confLogType = confLogTypes.get(0);
        }

        return confLogType;
    } catch (Exception ex2) {
        log.error("[getConferenceLogTypeByEventName]: " + ex2);
    }
    return null;
}

From source file:org.jasig.portlet.blackboardvcportlet.dao.impl.ConferenceUserDaoImpl.java

@Override
public Set<ConferenceUser> getUsersByPrimaryEmail(String email) {
    final TypedQuery<ConferenceUserImpl> query = this.createQuery(this.getUsersByPrimaryEmailQuery);
    query.setParameter(this.emailParameter, email.toUpperCase());

    final List<ConferenceUserImpl> resultList = query.getResultList();
    return new LinkedHashSet<ConferenceUser>(resultList);
}

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

public UserContacts getContactsByHash(String hash) {
    try {/*from   ww w.ja  va 2 s.c o  m*/

        String hql = "select c from UserContacts c " + "where c.hash like :hash ";

        TypedQuery<UserContacts> query = em.createQuery(hql, UserContacts.class);
        query.setParameter("hash", hash);
        List<UserContacts> ll = query.getResultList();

        if (ll.size() > 0) {
            return ll.get(0);
        }

    } catch (Exception e) {
        log.error("[getContactsByHash]", e);
    }
    return null;
}

From source file:org.jasig.portlet.notice.service.jpa.JpaNotificationDao.java

@Override
@Transactional(readOnly = true)//from   ww w  . j a v  a 2s  .c  o m
public List<JpaEntry> list(Integer page, Integer pageSize) {
    TypedQuery<JpaEntry> query = entityManager.createNamedQuery("JpaEntry.getAll", JpaEntry.class);

    if (page != null && pageSize != null) {
        query.setFirstResult(page * pageSize);
        query.setMaxResults(pageSize);
    }

    return query.getResultList();
}

From source file:edu.sabanciuniv.sentilab.sare.controllers.entitymanagers.AspectOpinionMinedCorpusController.java

/**
 * Finds the opinion mined corpus associated with a given corpus, lexicon, and engine code.
 * @param em the {@link EntityManager} to use.
 * @param corpus the {@link DocumentCorpus} being used to mine opinion.
 * @param lexicon the {@link AspectLexicon} being built.
 * @return the {@link AspectOpinionMinedCorpus} object found, if any; {@code null} otherwise.
 */// w  w w.  j  av  a 2s  . c om
public AspectOpinionMinedCorpus findMinedCorpus(EntityManager em, DocumentCorpus corpus, AspectLexicon lexicon,
        String engineCode) {
    Validate.notNull(em, CannedMessages.NULL_ARGUMENT, "em");
    Validate.notNull(corpus, CannedMessages.NULL_ARGUMENT, "corpus");
    Validate.notNull(lexicon, CannedMessages.NULL_ARGUMENT, "lexicon");

    TypedQuery<AspectOpinionMinedCorpus> query = em.createQuery(
            "SELECT mc FROM AspectOpinionMinedCorpus mc "
                    + "WHERE mc.baseStore=:corpus AND :lexicon MEMBER OF mc.referencedObjects",
            AspectOpinionMinedCorpus.class);
    query.setParameter("corpus", corpus).setParameter("lexicon", lexicon);

    for (AspectOpinionMinedCorpus minedCorpus : query.getResultList()) {
        if (StringUtils.equals(engineCode, minedCorpus.getEngineCode())) {
            return minedCorpus;
        }
    }

    return null;
}

From source file:com.devicehive.dao.rdbms.NetworkDaoRdbmsImpl.java

@Override
public List<NetworkWithUsersAndDevicesVO> getNetworksByIdsAndUsers(Long idForFiltering, Set<Long> networkId,
        Set<Long> permittedNetworks) {
    TypedQuery<Network> query = createNamedQuery(Network.class, "Network.getNetworksByIdsAndUsers",
            Optional.of(CacheConfig.bypass())).setParameter("userId", idForFiltering)
                    .setParameter("networkIds", networkId).setParameter("permittedNetworks", permittedNetworks);
    List<Network> result = query.getResultList();
    Stream<NetworkWithUsersAndDevicesVO> objectStream = result.stream()
            .map(Network::convertWithDevicesAndUsers);
    return objectStream.collect(Collectors.toList());
}