List of usage examples for javax.persistence Query setMaxResults
Query setMaxResults(int maxResult);
From source file:org.apache.roller.weblogger.business.jpa.JPAUserManagerImpl.java
public List getUsers(Weblog weblog, Boolean enabled, Date startDate, Date endDate, int offset, int length) throws WebloggerException { Query query = null; List results = null;// w w w .j a va 2 s.c o m // if we are doing date range then we must have an end date if (startDate != null && endDate == null) { endDate = new Date(); } List params = new ArrayList(); int size = 0; StringBuffer queryString = new StringBuffer(); StringBuffer whereClause = new StringBuffer(); if (weblog != null) { queryString.append("SELECT u FROM User u JOIN u.permissions p "); params.add(size++, weblog); whereClause.append(" WHERE p.website = ?" + size); } else { queryString.append("SELECT u FROM User u "); } if (enabled != null) { if (whereClause.length() == 0) { whereClause.append(" WHERE "); } else { whereClause.append(" AND "); } params.add(size++, enabled); whereClause.append("u.enabled = ?" + size); } if (startDate != null) { if (whereClause.length() == 0) { whereClause.append(" WHERE "); } else { whereClause.append(" AND "); } // if we are doing date range then we must have an end date if (endDate == null) { endDate = new Date(); } Timestamp start = new Timestamp(startDate.getTime()); Timestamp end = new Timestamp(endDate.getTime()); params.add(size++, start); whereClause.append("u.dateCreated > ?" + size); params.add(size++, end); whereClause.append(" AND u.dateCreated < ?" + size); } whereClause.append(" ORDER BY u.dateCreated DESC"); query = strategy.getDynamicQuery(queryString.toString() + whereClause.toString()); if (offset != 0) { query.setFirstResult(offset); } if (length != -1) { query.setMaxResults(length); } for (int i = 0; i < params.size(); i++) { query.setParameter(i + 1, params.get(i)); } return query.getResultList(); }
From source file:org.apache.roller.weblogger.business.jpa.JPAWeblogEntryManagerImpl.java
/** * @inheritDoc/*from ww w . ja v a 2 s .c o m*/ */ public List getPopularTags(Weblog website, Date startDate, int offset, int limit) throws WebloggerException { Query query = null; List queryResults = null; if (website != null) { if (startDate != null) { Timestamp start = new Timestamp(startDate.getTime()); query = strategy.getNamedQuery("WeblogEntryTagAggregate.getPopularTagsByWebsite&StartDate"); query.setParameter(1, website); query.setParameter(2, start); } else { query = strategy.getNamedQuery("WeblogEntryTagAggregate.getPopularTagsByWebsite"); query.setParameter(1, website); } } else { if (startDate != null) { Timestamp start = new Timestamp(startDate.getTime()); query = strategy.getNamedQuery("WeblogEntryTagAggregate.getPopularTagsByWebsiteNull&StartDate"); query.setParameter(1, start); } else { query = strategy.getNamedQuery("WeblogEntryTagAggregate.getPopularTagsByWebsiteNull"); } } if (offset != 0) { query.setFirstResult(offset); } if (limit != -1) { query.setMaxResults(limit); } queryResults = query.getResultList(); double min = Integer.MAX_VALUE; double max = Integer.MIN_VALUE; List results = new ArrayList(limit); for (Iterator iter = queryResults.iterator(); iter.hasNext();) { Object[] row = (Object[]) iter.next(); TagStat t = new TagStat(); t.setName((String) row[0]); t.setCount(((Number) row[1]).intValue()); min = Math.min(min, t.getCount()); max = Math.max(max, t.getCount()); results.add(t); } min = Math.log(1 + min); max = Math.log(1 + max); double range = Math.max(.01, max - min) * 1.0001; for (Iterator iter = results.iterator(); iter.hasNext();) { TagStat t = (TagStat) iter.next(); t.setIntensity((int) (1 + Math.floor(5 * (Math.log(1 + t.getCount()) - min) / range))); } // sort results by name, because query had to sort by total Collections.sort(results, tagStatNameComparator); return results; }
From source file:org.opencms.db.jpa.CmsUserDriver.java
/** * @see org.opencms.db.I_CmsUserDriver#searchUsers(org.opencms.db.CmsDbContext, org.opencms.file.CmsUserSearchParameters) *///from w w w .j ava2 s.com public List<CmsUser> searchUsers(CmsDbContext dbc, CmsUserSearchParameters searchParams) throws CmsDataAccessException { List<CmsUser> users = new ArrayList<CmsUser>(); try { CmsUserQueryBuilder builder = new CmsJpaUserQueryBuilder(); CmsPair<String, List<Object>> queryData = builder.createUserQuery(searchParams, false); Query q = m_sqlManager.createQueryWithParametersFromJPQL(dbc, queryData.getFirst(), queryData.getSecond()); // paging is done here, not in the query string q.setMaxResults(searchParams.getPageSize()); q.setFirstResult(searchParams.getPageSize() * (searchParams.getPage() - 1)); List<?> res = q.getResultList(); // create new Cms group objects for (Object singleRes : res) { CmsDAOUsers daoUser = null; if (singleRes instanceof Object[]) { Object[] resArray = (Object[]) singleRes; daoUser = (CmsDAOUsers) resArray[0]; } else { daoUser = (CmsDAOUsers) singleRes; } users.add(internalCreateUser(dbc, daoUser)); } } catch (PersistenceException e) { throw new CmsDataAccessException(Messages.get().container(Messages.ERR_JPA_PERSITENCE, e), e); } return users; }
From source file:gov.medicaid.services.impl.ProviderEnrollmentServiceBean.java
/** * This method gets all the providers that meet the search criteria. If none available, the search result will be * empty./* w ww . ja v a 2s . co m*/ * * @param user the user performing the action * @param criteria - the search criteria * @return - the applicable providers * * @throws IllegalArgumentException if any argument is null, or the page size and page number settings are invalid * @throws PortalServiceException for any errors encountered */ @SuppressWarnings("unchecked") public SearchResult<UserRequest> searchTickets(CMSUser user, ProviderSearchCriteria criteria) throws PortalServiceException { if (criteria == null) { throw new IllegalArgumentException("Criteria cannot be null."); } if (user == null || user.getRole() == null) { throw new IllegalArgumentException("User and the corresponding role cannot be null."); } if (Util.isNotBlank(criteria.getEnrollmentNumber()) && !Util.isDigits(criteria.getEnrollmentNumber())) { throw new IllegalArgumentException("Invalid number format for enrollment number."); } checkSortColumn(criteria, TICKET_COL_CNT); SearchResult<UserRequest> results = new SearchResult<UserRequest>(); results.setPageNumber(criteria.getPageNumber()); results.setPageSize(criteria.getPageSize()); String fromClause = "FROM ProviderProfile p LEFT JOIN p.riskLevel rl, Enrollment t LEFT JOIN t.requestType rt " + "LEFT JOIN t.status ts, Entity e LEFT JOIN e.providerType pt WHERE p.ticketId = t.ticketId " + "AND e.ticketId = p.ticketId AND p.profileId = e.profileId AND p.ticketId > 0"; StringBuilder countQuery = new StringBuilder("SELECT count(*) " + fromClause); appendCriteria(countQuery, user, criteria); Query count = getEm().createQuery(countQuery.toString()); bindParameters(count, user, criteria); results.setTotal(((Number) count.getSingleResult()).intValue()); StringBuilder fetchQuery = new StringBuilder( "SELECT NEW gov.medicaid.entities.UserRequest(t.ticketId, e.npi, t.submissionDate, " + "rt.description, ts.description, t.statusDate, rl.description, pt.description, " + "e.name, t.createdOn, rl.sortIndex, t.processInstanceId, t.profileReferenceId) " + fromClause); appendCriteria(fetchQuery, user, criteria); appendSorting(fetchQuery, criteria); Query items = getEm().createQuery(fetchQuery.toString()); bindParameters(items, user, criteria); if (criteria.getPageSize() > 0) { int offset = (criteria.getPageNumber() - 1) * criteria.getPageSize(); items.setFirstResult(offset); items.setMaxResults(criteria.getPageSize()); } results.setItems(items.getResultList()); return results; }
From source file:gov.medicaid.services.impl.ProviderEnrollmentServiceBean.java
/** * Search for practice./*from w w w .j a va2s . c o m*/ * * @param user the user performing the search * @param criteria the criteria filter * @return the matching practice results * @throws PortalServiceException for any errors encountered */ @SuppressWarnings("unchecked") public SearchResult<PracticeLookup> searchPractice(CMSUser user, PracticeSearchCriteria criteria) throws PortalServiceException { if (criteria == null) { throw new IllegalArgumentException("Criteria cannot be null."); } if (user == null || user.getRole() == null) { throw new IllegalArgumentException("User and the corresponding role cannot be null."); } if (criteria.getPageNumber() < 0 || (criteria.getPageNumber() > 0 && criteria.getPageSize() <= 0)) { throw new IllegalArgumentException("Invalid page number/page size combination."); } checkSortColumn(criteria, PRACTICE_COL_CNT); SearchResult<PracticeLookup> results = new SearchResult<PracticeLookup>(); results.setPageNumber(criteria.getPageNumber()); results.setPageSize(criteria.getPageSize()); String fromClause = "FROM Organization e LEFT JOIN e.contactInformation ci LEFT JOIN ci.address a " + "WHERE e.enrolled = 'Y'"; StringBuilder countQuery = new StringBuilder("SELECT count(*) " + fromClause); appendCriteria(countQuery, user, criteria); Query count = getEm().createQuery(countQuery.toString()); bindParameters(count, user, criteria); results.setTotal(((Number) count.getSingleResult()).intValue()); StringBuilder fetchQuery = new StringBuilder( "SELECT NEW gov.medicaid.entities.PracticeLookup(e.profileId, e.npi, e.name, " + "ci.address.line1, ci.address.line2, ci.address.city, ci.address.state, " + "ci.address.zipcode, ci.address.county, ci.phoneNumber, ci.faxNumber, " + "e.backgroundStudyId, e.backgroundClearanceDate, e.agencyId) " + fromClause); appendCriteria(fetchQuery, user, criteria); appendSorting(fetchQuery, criteria); Query items = getEm().createQuery(fetchQuery.toString()); bindParameters(items, user, criteria); if (criteria.getPageNumber() > 0) { int offset = (criteria.getPageNumber() - 1) * criteria.getPageSize(); items.setFirstResult(offset); items.setMaxResults(criteria.getPageSize()); } results.setItems(items.getResultList()); if (criteria.isAgency()) { populateContact(items.getResultList()); } return results; }
From source file:org.apache.roller.weblogger.business.jpa.JPAWeblogEntryManagerImpl.java
/** * @inheritDoc//from w w w. j av a2 s . co m */ public List getTags(Weblog website, String sortBy, String startsWith, int offset, int limit) throws WebloggerException { Query query = null; List queryResults = null; boolean sortByName = sortBy == null || !sortBy.equals("count"); List params = new ArrayList(); int size = 0; StringBuffer queryString = new StringBuffer(); queryString.append("SELECT w.name, SUM(w.total) FROM WeblogEntryTagAggregate w WHERE "); if (website != null) { params.add(size++, website.getId()); queryString.append(" w.weblog.id = ?").append(size); } else { queryString.append(" w.weblog IS NULL"); } if (startsWith != null && startsWith.length() > 0) { params.add(size++, startsWith + '%'); queryString.append(" AND w.name LIKE ?" + size); } if (sortBy != null && sortBy.equals("count")) { sortBy = "w.total DESC"; } else { sortBy = "w.name"; } queryString.append(" GROUP BY w.name, w.total ORDER BY " + sortBy); query = strategy.getDynamicQuery(queryString.toString()); for (int i = 0; i < params.size(); i++) { query.setParameter(i + 1, params.get(i)); } if (offset != 0) { query.setFirstResult(offset); } if (limit != -1) { query.setMaxResults(limit); } queryResults = query.getResultList(); List results = new ArrayList(); for (Iterator iter = queryResults.iterator(); iter.hasNext();) { Object[] row = (Object[]) iter.next(); TagStat ce = new TagStat(); ce.setName((String) row[0]); // The JPA query retrieves SUM(w.total) always as long ce.setCount(((Long) row[1]).intValue()); results.add(ce); } if (sortByName) { Collections.sort(results, tagStatNameComparator); } else { Collections.sort(results, tagStatCountReverseComparator); } return results; }
From source file:com.tea.landlordapp.repository.mysql.ApplicationDaoImpl.java
@SuppressWarnings("unchecked") private List<Application> findApplications(String startSql, Integer id, String condition, List<SearchTerm> searchTerms, Integer pageNo, Integer sortBy, String sortType, User user) { if (StringUtils.isBlank(condition)) { condition = "and"; }/*from w w w .ja va 2 s . co m*/ // String addlQuery = " "; final StringBuilder build = new StringBuilder(" "); if (!ObjectUtils.equals(searchTerms, null) && searchTerms.size() > 0) { try { int countSearchTerm = 0; for (final SearchTerm s : searchTerms) { if (++countSearchTerm == 1) { build.append("AND"); } else { build.append(condition); } if (s.getCriteria().contains("].lastName")) { final String encLN = s.getValueAsString(); build.append( " a.id in (select ap.application.id from Applicant ap where upper(ap.lastName) " + s.getModifier() + " " + encLN + ") "); } else if (s.getCriteria().contains("Date")) { build.append(" " + "date_format(" + s.getCriteria() + ", '%m/%d/%Y') " + s.getModifier() + " " + s.getValueAsString() + " "); } else { build.append( " " + s.getCriteria() + " " + s.getModifier() + " " + s.getValueAsString() + " "); } } } catch (final Exception ex) { logger.error("Unable to create additional query..."); build.append(""); } } // Append Sort By if (sortBy == 3 || sortBy == 4 || sortBy == 5) { // sort by firstName, lastName, ssn // Note: order by a.applications[0].firstName is not supported. build.append(" AND app.application.id = a.id AND app.applicantType like 'Primary' order by " + getViewApplicationsSortOptions().get(sortBy) + " " + sortType); } else { build.append(" order by " + getViewApplicationsSortOptions().get(sortBy) + " " + sortType); } final String addlQuery = build.toString(); logger.debug("findApplications query is.. " + startSql + addlQuery); final Query query = em.createQuery(startSql + addlQuery); query.setFirstResult(pageNo * 10); query.setMaxResults(10); query.setParameter("id", id); if (user != null) query.setParameter("user", user); return query.getResultList(); }
From source file:org.medici.bia.dao.image.ImageDAOJpaImpl.java
/** * {@inheritDoc}//from ww w .jav a 2s . co m */ @SuppressWarnings("unchecked") @Override public <T extends VolumeExplorer> Image findImage(T explorer) throws PersistenceException { // If total is null we need to obtain total and partial total by type (rubricario and folio)... if (explorer.getTotal() == null) { this.updateExplorerTotals(explorer); } Image image = explorer.getImage(); StringBuilder stringBuilder = new StringBuilder(" FROM Image WHERE"); stringBuilder.append(" volNum = :volNum"); if (explorer.getVolLetExt() == null || !StringUtils.isEmpty(explorer.getVolLetExt().trim())) { stringBuilder.append(" AND volLetExt") .append(explorer.getVolLetExt() == null ? " IS NULL" : " = :volLetExt"); } if (image.getImageProgTypeNum() != null) { // folio number is provided --> the query search by this criterium if (image.getInsertNum() == null || !StringUtils.isEmpty(image.getInsertNum().trim())) { stringBuilder.append(" AND insertNum") .append(image.getInsertNum() == null ? " IS NULL" : " = :insertNum"); } if (image.getInsertLet() == null || !StringUtils.isEmpty(image.getInsertLet().trim())) { stringBuilder.append(" AND insertLet") .append(image.getInsertLet() == null ? " IS NULL" : " = :insertLet"); } if (image.getImageType() != null) { stringBuilder.append(" AND imageType = :imageType"); } stringBuilder.append(" AND imageProgTypeNum = :imageProgTypeNum"); if (image.getMissedNumbering() == null || !StringUtils.isEmpty(image.getMissedNumbering().trim())) { stringBuilder.append(" AND missedNumbering") .append(image.getMissedNumbering() == null ? " IS NULL" : " = :missedNumbering"); } if (image.getImageRectoVerso() != null) { // imageRectoVerso cannot be null in tblImages stringBuilder.append(" AND imageRectoVerso = :imageRectoVerso"); } } else if (image.getImageOrder() != null) { // folio numnber is not provided --> we first consider image order search filter stringBuilder.append(" AND imageOrder = :imageOrder"); } else if (!org.medici.bia.common.util.StringUtils.isNullableString(image.getImageName())) { // imageOrder is not provided --> we consider imageName search filter stringBuilder.append(" AND imageName LIKE '%").append(image.getImageName().trim()).append("%'"); } else { // no search filter is provided --> we set 1 for imageOrder stringBuilder.append(" AND imageOrder = 1"); } logger.debug("FindImages from documentExplorer query: " + stringBuilder.toString()); Query query = getEntityManager().createQuery(stringBuilder.toString()); query.setParameter("volNum", explorer.getVolNum()); if (!org.medici.bia.common.util.StringUtils.isNullableString(explorer.getVolLetExt())) { query.setParameter("volLetExt", explorer.getVolLetExt()); } if (image.getImageProgTypeNum() != null) { if (!org.medici.bia.common.util.StringUtils.isNullableString(image.getInsertNum())) { query.setParameter("insertNum", image.getInsertNum().trim()); } if (!org.medici.bia.common.util.StringUtils.isNullableString(image.getInsertLet())) { query.setParameter("insertLet", image.getInsertLet().trim()); } if (image.getImageType() != null) { query.setParameter("imageType", image.getImageType()); } query.setParameter("imageProgTypeNum", image.getImageProgTypeNum()); if (!org.medici.bia.common.util.StringUtils.isNullableString(image.getMissedNumbering())) { query.setParameter("missedNumbering", image.getMissedNumbering()); } if (image .getImageRectoVerso() != null/* && !Image.ImageRectoVerso.N.equals(image.getImageRectoVerso())*/) { query.setParameter("imageRectoVerso", image.getImageRectoVerso()); } List<Image> result = (List<Image>) query.getResultList(); if (result.size() > 0) { return result.get(0); } return null; } if (image.getImageOrder() != null) { // imageOrder is provided query.setParameter("imageOrder", image.getImageOrder()); } // imageOrder provided or image name provided or no searching criteria is provided query.setFirstResult(0); query.setMaxResults(1); try { return (Image) query.getSingleResult(); } catch (NoResultException noResultExcepion) { } return null; }
From source file:org.apache.roller.weblogger.business.jpa.JPAWeblogEntryManagerImpl.java
/** * @inheritDoc//from w w w. ja v a 2 s . c o m */ public List getMostCommentedWeblogEntries(Weblog website, Date startDate, Date endDate, int offset, int length) throws WebloggerException { Query query = null; List queryResults = null; if (endDate == null) endDate = new Date(); if (website != null) { if (startDate != null) { Timestamp start = new Timestamp(startDate.getTime()); Timestamp end = new Timestamp(endDate.getTime()); query = strategy .getNamedQuery("WeblogEntryComment.getMostCommentedWeblogEntryByWebsite&EndDate&StartDate"); query.setParameter(1, website); query.setParameter(2, end); query.setParameter(3, start); } else { Timestamp end = new Timestamp(endDate.getTime()); query = strategy.getNamedQuery("WeblogEntryComment.getMostCommentedWeblogEntryByWebsite&EndDate"); query.setParameter(1, website); query.setParameter(2, end); } } else { if (startDate != null) { Timestamp start = new Timestamp(startDate.getTime()); Timestamp end = new Timestamp(endDate.getTime()); query = strategy.getNamedQuery("WeblogEntryComment.getMostCommentedWeblogEntryByEndDate&StartDate"); query.setParameter(1, end); query.setParameter(2, start); } else { Timestamp end = new Timestamp(endDate.getTime()); query = strategy.getNamedQuery("WeblogEntryComment.getMostCommentedWeblogEntryByEndDate"); query.setParameter(1, end); } } if (offset != 0) { query.setFirstResult(offset); } if (length != -1) { query.setMaxResults(length); } queryResults = query.getResultList(); List results = new ArrayList(); for (Iterator iter = queryResults.iterator(); iter.hasNext();) { Object[] row = (Object[]) iter.next(); StatCount sc = new StatCount((String) row[1], // weblog handle (String) row[2], // entry anchor (String) row[3], // entry title "statCount.weblogEntryCommentCountType", // stat desc ((Long) row[0]).longValue()); // count sc.setWeblogHandle((String) row[1]); results.add(sc); } // Original query ordered by desc count. // JPA QL doesn't allow queries to be ordered by agregates; do it in memory Collections.sort(results, statCountCountReverseComparator); return results; }
From source file:org.apache.roller.weblogger.business.jpa.JPAWeblogEntryManagerImpl.java
public List getNextPrevEntries(WeblogEntry current, String catName, String locale, int maxEntries, boolean next) throws WebloggerException { if (current == null) { log.debug("WeblogEntry current cannot be null"); return Collections.emptyList(); }/* ww w.jav a 2s . com*/ Query query = null; List results = null; WeblogCategory category = null; if (catName != null && !catName.trim().equals("/")) { category = getWeblogCategoryByPath(current.getWebsite(), null, catName); } List params = new ArrayList(); int size = 0; StringBuffer queryString = new StringBuffer(); StringBuffer whereClause = new StringBuffer(); queryString.append("SELECT e FROM WeblogEntry e WHERE "); params.add(size++, current.getWebsite()); whereClause.append("e.website = ?" + size); params.add(size++, WeblogEntry.PUBLISHED); whereClause.append(" AND e.status = ?" + size); if (next) { params.add(size++, current.getPubTime()); whereClause.append(" AND e.pubTime > ?" + size); } else { params.add(size++, current.getPubTime()); whereClause.append(" AND e.pubTime < ?" + size); } if (catName != null && !catName.trim().equals("/")) { category = getWeblogCategoryByPath(current.getWebsite(), catName); if (category != null) { params.add(size++, category); whereClause.append(" AND e.category = ?" + size); } else { throw new WebloggerException("Cannot find category: " + catName); } } if (locale != null) { params.add(size++, locale + '%'); whereClause.append(" AND e.locale like ?" + size); } if (next) { whereClause.append(" ORDER BY e.pubTime ASC"); } else { whereClause.append(" ORDER BY e.pubTime DESC"); } query = strategy.getDynamicQuery(queryString.toString() + whereClause.toString()); for (int i = 0; i < params.size(); i++) { query.setParameter(i + 1, params.get(i)); } query.setMaxResults(maxEntries); return query.getResultList(); }