Example usage for javax.persistence Query setMaxResults

List of usage examples for javax.persistence Query setMaxResults

Introduction

In this page you can find the example usage for javax.persistence Query setMaxResults.

Prototype

Query setMaxResults(int maxResult);

Source Link

Document

Set the maximum number of results to retrieve.

Usage

From source file:org.opentides.persistence.impl.AuditLogDAOImpl.java

@SuppressWarnings("unchecked")
public final List<AuditLog> findByExample(AuditLog example, int start, int total) {
    if (example instanceof Searchable) {
        Searchable criteria = (Searchable) example;
        String whereClause = CrudUtil.buildJpaQueryString(criteria, false);
        String orderClause = " " + appendOrderToExample(example);
        String append = appendClauseToExample(example);
        whereClause = doSQLAppend(whereClause, append);
        if (_log.isDebugEnabled())
            _log.debug("QBE >> " + whereClause + orderClause);
        Query query = getEntityManager().createQuery("from AuditLog obj " + whereClause + orderClause);
        if (start > -1)
            query.setFirstResult(start);
        if (total > -1)
            query.setMaxResults(total);
        return query.getResultList();
    } else {/* w  w  w  . ja  v  a  2 s  . com*/
        throw new InvalidImplementationException(
                "Parameter example [" + example.getClass().getName() + "] is not an instance of Searchable");
    }
}

From source file:com.sun.socialsite.business.impl.JPASocialSiteActivityManagerImpl.java

/**
 * Note: using SuppressWarnings annotation because the JPA API is not genericized.
 *//*from w  w w . java 2s  .c o  m*/
@SuppressWarnings(value = "unchecked")
public SocialSiteActivity getLatestStatus(Profile profile) throws SocialSiteException {
    if (profile == null) {
        throw new SocialSiteException("profile is null");
    }
    Query query = strategy.getNamedQuery("Activity.getStatusByProfile");
    query.setParameter(1, profile);
    query.setParameter(2, SocialSiteActivity.STATUS);
    query.setFirstResult(0);
    query.setMaxResults(1);
    List<SocialSiteActivity> ac = (List<SocialSiteActivity>) query.getResultList();
    if ((ac != null) && (ac.size() > 0)) {
        return ac.get(0);
    } else {
        return null;
    }
}

From source file:ltistarter.lti.LTIDataService.java

/**
 * Loads up the data which is referenced in this LTI request (assuming it can be found in the DB)
 *
 * @param lti the LTIRequest which we are populating
 * @return true if any data was loaded OR false if none could be loaded (because no matching data was found or the input keys are not set)
 *//*from  www .j av a 2s  .c  o m*/
@Transactional
public boolean loadLTIDataFromDB(LTIRequest lti) {
    assert repos != null;
    lti.loaded = false;
    if (lti.ltiConsumerKey == null) {
        // don't even attempt this without a key, it's pointless
        log.info("LTIload: No key to load lti.results for");
        return false;
    }
    boolean includesService = (lti.ltiServiceId != null);
    boolean includesSourcedid = (lti.ltiSourcedid != null);

    StringBuilder sb = new StringBuilder();
    sb.append("SELECT k, c, l, m, u"); //k.keyId, k.keyKey, k.secret, c.contextId, c.title AS contextTitle, l.linkId, l.title AS linkTitle, u.userId, u.displayName AS userDisplayName, u.email AS userEmail, u.subscribe, u.userSha256, m.membershipId, m.role, m.roleOverride"); // 15

    if (includesService) {
        sb.append(", s"); //, s.serviceId, s.serviceKey AS service"); // 2
    }
    if (includesSourcedid) {
        sb.append(", r"); //, r.lti.resultId, r.sourcedid, r.grade"); // 3
    }
    /*
    if (includeProfile) {
    sb.append(", p"); //", p.profileId, p.displayName AS profileDisplayName, p.email AS profileEmail, p.subscribe AS profileSubscribe"); // 4
    }*/

    sb.append(" FROM LtiKeyEntity k " + "LEFT JOIN k.contexts c ON c.contextSha256 = :context " + // LtiContextEntity
            "LEFT JOIN c.links l ON l.linkSha256 = :link " + // LtiLinkEntity
            "LEFT JOIN c.memberships m " + // LtiMembershipEntity
            "LEFT JOIN m.user u ON u.userSha256 = :user " // LtiUserEntity
    );

    if (includesService) {
        sb.append(" LEFT JOIN k.services s ON s.serviceSha256 = :service"); // LtiServiceEntity
    }
    if (includesSourcedid) {
        sb.append(" LEFT JOIN u.results r ON r.sourcedidSha256 = :sourcedid"); // LtiResultEntity
    }
    /*
    if (includeProfile) {
    sb.append(" LEFT JOIN u.profile p"); // ProfileEntity
    }*/
    sb.append(" WHERE k.keySha256 = :key AND (m IS NULL OR (m.context = c AND m.user = u))");
    /*
    if (includeProfile) {
    sb.append(" AND (u IS NULL OR u.profile = p)");
    }*/

    String sql = sb.toString();
    Query q = repos.entityManager.createQuery(sql);
    q.setMaxResults(1);
    q.setParameter("key", BaseEntity.makeSHA256(lti.ltiConsumerKey));
    q.setParameter("context", BaseEntity.makeSHA256(lti.ltiContextId));
    q.setParameter("link", BaseEntity.makeSHA256(lti.ltiLinkId));
    q.setParameter("user", BaseEntity.makeSHA256(lti.ltiUserId));
    if (includesService) {
        q.setParameter("service", BaseEntity.makeSHA256(lti.ltiServiceId));
    }
    if (includesSourcedid) {
        q.setParameter("sourcedid", BaseEntity.makeSHA256(lti.ltiSourcedid));
    }
    @SuppressWarnings("unchecked")
    List<Object[]> rows = q.getResultList();
    if (rows == null || rows.isEmpty()) {
        log.info("LTIload: No lti.results found for key=" + lti.ltiConsumerKey);
    } else {
        // k, c, l, m, u, s, r
        Object[] row = rows.get(0);
        if (row.length > 0)
            lti.key = (LtiKeyEntity) row[0];
        if (row.length > 1)
            lti.context = (LtiContextEntity) row[1];
        if (row.length > 2)
            lti.link = (LtiLinkEntity) row[2];
        if (row.length > 3)
            lti.membership = (LtiMembershipEntity) row[3];
        if (row.length > 4)
            lti.user = (LtiUserEntity) row[4];
        if (includesService && includesSourcedid) {
            if (row.length > 5)
                lti.service = (LtiServiceEntity) row[5];
            if (row.length > 6)
                lti.result = (LtiResultEntity) row[6];
        } else if (includesService) {
            if (row.length > 5)
                lti.service = (LtiServiceEntity) row[5];
        } else if (includesSourcedid) {
            if (row.length > 5)
                lti.result = (LtiResultEntity) row[5];
        }

        // handle SPECIAL post lookup processing
        // If there is an appropriate role override variable, we use that role
        if (lti.membership != null && lti.membership.getRoleOverride() != null) {
            int roleOverrideNum = lti.membership.getRoleOverride();
            if (roleOverrideNum > lti.userRoleNumber) {
                lti.userRoleNumber = roleOverrideNum;
            }
        }

        // check if the loading lti.resulted in a complete set of LTI data
        lti.checkCompleteLTIRequest(true);
        lti.loaded = true;
        log.info("LTIload: loaded data for key=" + lti.ltiConsumerKey + " and context=" + lti.ltiContextId
                + ", complete=" + lti.complete);
    }
    return lti.loaded;
}

From source file:com.sun.socialsite.business.impl.JPAProfileManagerImpl.java

/**
 * Note: using SuppressWarnings annotation because the JPA API is not genericized.
 *//*  w ww.  j a v a 2  s .com*/
@SuppressWarnings(value = "unchecked")
public List<Profile> getProfiles(int offset, int length) throws SocialSiteException {
    Query query = strategy.getNamedQuery("Profile.getAll");
    if (offset != 0)
        query.setFirstResult(offset);
    if (length != -1)
        query.setMaxResults(length);
    return (List<Profile>) query.getResultList();
}

From source file:com.sun.socialsite.business.impl.JPAProfileManagerImpl.java

/**
 * Note: using SuppressWarnings annotation because the JPA API is not genericized.
 *///from   w w w  .ja  v a2  s.  c om
@SuppressWarnings(value = "unchecked")
public List<Profile> getOldestProfiles(int offset, int length) throws SocialSiteException {
    Query query = strategy.getNamedQuery("Profile.getOldest");
    if (offset != 0)
        query.setFirstResult(offset);
    if (length != -1)
        query.setMaxResults(length);
    return (List<Profile>) query.getResultList();
}

From source file:de.iai.ilcd.model.dao.UserGroupDao.java

@SuppressWarnings("unchecked")
public List<UserGroup> getGroups(Organization org, Integer first, Integer pageSize) {
    if (org == null) {
        return null;
    }/*from   www .  ja v  a2 s  . c  o m*/
    EntityManager em = PersistenceUtil.getEntityManager();

    try {
        Query q = em.createQuery(
                "SELECT DISTINCT g FROM UserGroup g WHERE g.organization.id = :orgId ORDER BY g.groupName");
        q.setParameter("orgId", org.getId());
        if (first != null) {
            q.setFirstResult(first.intValue());
        }
        if (pageSize != null) {
            q.setMaxResults(pageSize.intValue());
        }
        return (List<UserGroup>) q.getResultList();
    } catch (Exception e) {
        return null;
    }
}

From source file:fr.mby.opa.picsimpl.dao.DbProposalDao.java

@Override
public ProposalBag findLastBag(final long albumId) {
    final EmCallback<ProposalBag> emCallback = new EmCallback<ProposalBag>(this.getEmf()) {

        @Override//from  w w w.jav a2s  .  c om
        @SuppressWarnings("unchecked")
        protected ProposalBag executeWithEntityManager(final EntityManager em) throws PersistenceException {
            final Query findLastBagQuery = em.createNamedQuery(ProposalBag.FIND_LAST_ALBUM_BAG);
            findLastBagQuery.setParameter("albumId", albumId);
            findLastBagQuery.setMaxResults(1);

            final ProposalBag bag = Iterables.getFirst(findLastBagQuery.getResultList(), null);
            return bag;
        }
    };

    return emCallback.getReturnedValue();
}

From source file:org.messic.server.datamodel.jpaimpl.DAOJPAAlbum.java

@Override
@Transactional/*from  w  w w . j av a  2 s.  com*/
public List<MDOAlbum> getRecent(String username, int maxAlbums) {
    Query query = entityManager.createQuery(
            "from MDOAlbum as a where (a.owner.login = :userName) AND (a.created is not null)  ORDER BY (a.created)");
    query.setParameter("userName", username);
    query.setMaxResults(maxAlbums);

    @SuppressWarnings("unchecked")
    List<MDOAlbum> results = query.getResultList();
    return results;
}

From source file:co.edu.uniandes.csw.uniandes.sport.service._SportService.java

@GET
public Response getSports(@Context HttpHeaders httpHeaders, @QueryParam("page") Integer page,
        @QueryParam("maxRecords") Integer maxRecords) {
    //      Imprime el header que ha enviado el usuario desde el cliente
    try {//from ww w  . ja va2s. c  om

        Subject currentUser = SecurityUtils.getSubject();
        Usuario user = (Usuario) currentUser.getPrincipal();
        String tenant = user.getTenant();
        Map<String, Object> emProperties = new HashMap<String, Object>();
        emProperties.put("eclipselink.tenant-id", tenant);//Asigna un valor al multitenant
        entityManager = PersistenceManager.getInstance().getEntityManagerFactory()
                .createEntityManager(emProperties);

        Query count = entityManager.createQuery("select count(u) from SportEntity u");
        Long regCount = 0L;
        regCount = Long.parseLong(count.getSingleResult().toString());
        Query q = entityManager.createQuery("select u from SportEntity u");
        if (page != null && maxRecords != null) {
            q.setFirstResult((page - 1) * maxRecords);
            q.setMaxResults(maxRecords);
        }
        SportPageDTO response = new SportPageDTO();
        response.setTotalRecords(regCount);
        response.setRecords(SportConverter.entity2PersistenceDTOList(q.getResultList()));
        String json = new Gson().toJson(response);
        return Response.status(200).header("Access-Control-Allow-Origin", "*").entity(json).build();

    } catch (Exception e) {
        e.printStackTrace();
        return Response.status(401).header("Access-Control-Allow-Origin", "*").entity("You need Authenticated")
                .build();
    }
}

From source file:eu.planets_project.tb.impl.persistency.ExperimentPersistencyImpl.java

@SuppressWarnings("unchecked")
public List<Experiment> getPagedExperiments(int firstRow, int numberOfRows, String sortField,
        boolean descending) {
    log.info("Searching for experiments that match: " + firstRow + "," + numberOfRows + " : " + sortField
            + " : " + descending);
    // Execute the query:
    Query query = manager.createQuery("FROM ExperimentImpl AS e " + createOrderBy(sortField, descending));
    query.setFirstResult(firstRow);// w w  w .  jav  a  2s  .c o m
    query.setMaxResults(numberOfRows);
    List<Experiment> resultList = query.getResultList();
    log.info("Search complete.");
    return resultList;

    /*
    String propertyName;
    if( "experimenter".equals(sortField) ) {
    //            this.findExperiment(1).getExperimentSetup().getBasicProperties().getExperimenter();
    propertyName = "expSetup.basicProperties.sExpName";
    } else {
    //          this.findExperiment(1).getExperimentSetup().getBasicProperties().getExperimentName();
    propertyName = "expSetup.basicProperties.sExpName";
    }
    Order order;
    if( descending ) {
    //    query.setParameter("deasc", "descending");
    order = Order.asc(propertyName);
    } else {
    //    query.setParameter("deasc", "ascending");
    order = Order.desc(propertyName);
    }
            
    Session hibernateSession = null;
    if (manager.getDelegate() instanceof org.hibernate.ejb.HibernateEntityManager) {
    hibernateSession = ((org.hibernate.ejb.HibernateEntityManager) manager
            .getDelegate()).getSession();
    } else {
    hibernateSession = (org.hibernate.Session) manager.getDelegate();
    }
            
    return hibernateSession.createCriteria(ExperimentImpl.class)
    .addOrder( order )
    .setFirstResult(firstRow)
    .setMaxResults(numberOfRows)
    .list();
    */
}