List of usage examples for org.hibernate Query setFetchSize
Query<R> setFetchSize(int fetchSize);
From source file:org.gbif.portal.dao.DAOUtils.java
License:Open Source License
/** * Process results, scrolling through each record in turn only loading that specific record. * /*from w w w.j a v a 2 s.c o m*/ * @param resultsOutputter * @param session * @param query * @param associationTraverser * @param batchSize * @throws IOException */ public static void scrollResults(final ResultsOutputter resultsOutputter, Session session, Query query, AssociationTraverser associationTraverser, int batchSize) throws IOException { query.setReadOnly(true); query.setFetchSize(batchSize); //Using scrollable results to prevent initiation of all model objects ScrollableResults sr = query.scroll(ScrollMode.FORWARD_ONLY); //go to beginning of resultset boolean isNotEmpty = sr.first(); if (!isNotEmpty) { //this is necessary due to a bug with ScrollableResults //allowing continuous scrolling over an empty resultset. genius. return; } //iterate through the results processScrollableResults(resultsOutputter, session, sr, associationTraverser, batchSize); //check for a chain if (resultsOutputter instanceof ChainableResultsOutputter) { ChainableResultsOutputter cro = (ChainableResultsOutputter) resultsOutputter; ResultsOutputter nextResultsOutputter = cro.getNextResultsOutputter(); while (nextResultsOutputter != null && !cro.isChainInOnePass()) { //back to the start sr.first(); processScrollableResults(nextResultsOutputter, session, sr, associationTraverser, batchSize); if (resultsOutputter instanceof ChainableResultsOutputter) { cro = (ChainableResultsOutputter) resultsOutputter; if (!cro.isChainInOnePass()) nextResultsOutputter = cro.getNextResultsOutputter(); else nextResultsOutputter = null; } else { nextResultsOutputter = null; } } } if (associationTraverser != null) associationTraverser.reset(); //close the results set sr.close(); }
From source file:org.jboss.aerogear.unifiedpush.jpa.dao.impl.JPAInstallationDao.java
License:Apache License
@Override public ResultsStream.QueryBuilder<String> findAllDeviceTokenForVariantIDByCriteria(String variantID, List<String> categories, List<String> aliases, List<String> deviceTypes, final int maxResults, String lastTokenFromPreviousBatch) { // the required part: Join + all tokens for variantID; final StringBuilder jpqlString = new StringBuilder(FIND_ALL_DEVICES_FOR_VARIANT_QUERY); final Map<String, Object> parameters = new LinkedHashMap<String, Object>(); parameters.put("variantID", variantID); // apend query conditions based on specified message parameters appendDynamicQuery(jpqlString, parameters, categories, aliases, deviceTypes); // sort on ids so that we can handle paging properly if (lastTokenFromPreviousBatch != null) { jpqlString.append(" AND installation.deviceToken > :lastTokenFromPreviousBatch"); parameters.put("lastTokenFromPreviousBatch", lastTokenFromPreviousBatch); }//from w ww . jav a 2 s . com jpqlString.append(" ORDER BY installation.deviceToken ASC"); return new ResultsStream.QueryBuilder<String>() { private Integer fetchSize = null; @Override public ResultsStream.QueryBuilder<String> fetchSize(int fetchSize) { this.fetchSize = fetchSize; return this; } @Override public ResultsStream<String> executeQuery() { Query hibernateQuery = JPAInstallationDao.this.createHibernateQuery(jpqlString.toString()); hibernateQuery.setMaxResults(maxResults); for (Entry<String, Object> parameter : parameters.entrySet()) { Object value = parameter.getValue(); if (value instanceof Collection<?>) { hibernateQuery.setParameterList(parameter.getKey(), (Collection<?>) parameter.getValue()); } else { hibernateQuery.setParameter(parameter.getKey(), parameter.getValue()); } } hibernateQuery.setReadOnly(true); if (fetchSize != null) { hibernateQuery.setFetchSize(fetchSize); } final ScrollableResults results = hibernateQuery.scroll(ScrollMode.FORWARD_ONLY); return new ResultsStream<String>() { @Override public boolean next() throws ResultStreamException { return results.next(); } @Override public String get() throws ResultStreamException { return (String) results.get()[0]; } }; } }; }
From source file:org.ng200.openolympus.services.TaskService.java
License:Open Source License
@PreAuthorize(SecurityExpressionConstants.IS_ADMIN) @Transactional/* w ww. j a v a2 s . c om*/ public void rejudgeTask(final Task task) throws ExecutionException, IOException { final Lock lock = task.writeLock(); lock.lock(); try { this.verdictRepository.flush(); this.solutionRepository.flush(); this.verdictRepository.deleteBySolutionTask(task); this.verdictRepository.flush(); final StatelessSession session = ((Session) this.entityManager.getDelegate()).getSessionFactory() .openStatelessSession(); try { final Query query = session.createQuery("from Solution where task_id=:taskID"); query.setParameter("taskID", task.getId()); query.setFetchSize(Integer.valueOf(1000)); query.setReadOnly(false); final ScrollableResults results = query.scroll(ScrollMode.FORWARD_ONLY); try { while (results.next()) { final Solution solution = (Solution) results.get(0); this.testingService.testSolutionOnAllTests(solution); } } finally { results.close(); } } finally { session.close(); } } finally { lock.unlock(); } }
From source file:org.openbravo.common.datasource.ReturnToVendorPickAndEditDataSource.java
License:Open Source License
private List<Map<String, Object>> getReceiptLines(Order order, Set<Organization> organizations, String where, Map<String, String> filterCriteria, String sortBy, int startRow, int endRow) { List<Map<String, Object>> result = new ArrayList<Map<String, Object>>(); OBContext.setAdminMode(true);/*from w ww . j a v a2 s .c om*/ try { final StringBuilder hqlString = new StringBuilder(); hqlString.append("select iol"); hqlString.append(" from MaterialMgmtShipmentInOutLine as iol"); hqlString.append(" join iol.shipmentReceipt as io"); // Adds joins when required by filters hqlString.append(getJoinArgumentsFromFilters(filterCriteria, sortBy)); // Starting where clause hqlString.append(" where io.businessPartner = :businessPartner"); hqlString.append(" and io.processed = true"); hqlString.append(" and io.documentStatus <> 'VO'"); hqlString.append(" and io.salesTransaction = false"); hqlString.append(" and iol.organization in :organizations"); hqlString.append( " and not exists (select 1 from OrderLine as ol where ol.salesOrder = :order and ol.goodsShipmentLine = iol)"); if (where != null && !"".equals(where) && !"null".equalsIgnoreCase(where)) { hqlString.append(" and " + where); } // Adds filters hqlString.append(getWhereArgumentsFromFilters(filterCriteria)); // Adds ordering hqlString.append(getOrderBy(sortBy)); final Session session = OBDal.getInstance().getSession(); final Query query = session.createQuery(hqlString.toString()); query.setParameter("order", order); query.setParameter("businessPartner", order.getBusinessPartner()); query.setParameterList("organizations", organizations); query.setFirstResult(startRow); query.setMaxResults(endRow - startRow); query.setFetchSize(endRow - startRow); for (Object o : query.list()) { ShipmentInOutLine inOutLine = (ShipmentInOutLine) o; result.add(getGridmap(inOutLine, null)); } } finally { OBContext.restorePreviousMode(); } return result; }
From source file:org.openbravo.costing.CostingRuleProcess.java
License:Open Source License
private ScrollableResults getStockLines(Set<String> childOrgs, Date date) { StringBuffer select = new StringBuffer(); select.append("select trx." + MaterialTransaction.PROPERTY_PRODUCT + ".id"); select.append(", trx." + MaterialTransaction.PROPERTY_ATTRIBUTESETVALUE + ".id"); select.append(", trx." + MaterialTransaction.PROPERTY_UOM + ".id"); select.append(", trx." + MaterialTransaction.PROPERTY_ORDERUOM + ".id"); select.append(", trx." + MaterialTransaction.PROPERTY_STORAGEBIN + ".id"); select.append(", loc." + Locator.PROPERTY_WAREHOUSE + ".id"); select.append(", sum(trx." + MaterialTransaction.PROPERTY_MOVEMENTQUANTITY + ")"); select.append(", sum(trx." + MaterialTransaction.PROPERTY_ORDERQUANTITY + ")"); select.append(" from " + MaterialTransaction.ENTITY_NAME + " as trx"); select.append(" join trx." + MaterialTransaction.PROPERTY_STORAGEBIN + " as loc"); select.append(" where trx." + MaterialTransaction.PROPERTY_ORGANIZATION + ".id in (:orgs)"); if (date != null) { select.append(" and trx." + MaterialTransaction.PROPERTY_MOVEMENTDATE + " < :date"); }// ww w. j a va2 s. c om select.append(" and trx." + MaterialTransaction.PROPERTY_PRODUCT + ".productType = 'I'"); select.append(" and trx." + MaterialTransaction.PROPERTY_PRODUCT + ".stocked = true"); select.append(" group by trx." + MaterialTransaction.PROPERTY_PRODUCT + ".id"); select.append(", trx." + MaterialTransaction.PROPERTY_ATTRIBUTESETVALUE + ".id"); select.append(", trx." + MaterialTransaction.PROPERTY_UOM + ".id"); select.append(", trx." + MaterialTransaction.PROPERTY_ORDERUOM + ".id"); select.append(", trx." + MaterialTransaction.PROPERTY_STORAGEBIN + ".id"); select.append(", loc." + Locator.PROPERTY_WAREHOUSE + ".id"); select.append(" having "); select.append(" sum(trx." + MaterialTransaction.PROPERTY_MOVEMENTQUANTITY + ") <> 0"); select.append(" or sum(trx." + MaterialTransaction.PROPERTY_ORDERQUANTITY + ") <> 0"); select.append(" order by loc." + Locator.PROPERTY_WAREHOUSE + ".id"); select.append(", trx." + MaterialTransaction.PROPERTY_PRODUCT + ".id"); select.append(", trx." + MaterialTransaction.PROPERTY_STORAGEBIN + ".id"); select.append(", trx." + MaterialTransaction.PROPERTY_ATTRIBUTESETVALUE + ".id"); select.append(", trx." + MaterialTransaction.PROPERTY_UOM + ".id"); select.append(", trx." + MaterialTransaction.PROPERTY_ORDERUOM + ".id"); Query stockLinesQry = OBDal.getInstance().getSession().createQuery(select.toString()); stockLinesQry.setParameterList("orgs", childOrgs); if (date != null) { stockLinesQry.setTimestamp("date", date); } stockLinesQry.setFetchSize(1000); ScrollableResults stockLines = stockLinesQry.scroll(ScrollMode.FORWARD_ONLY); return stockLines; }
From source file:org.openbravo.costing.FixBackdatedTransactionsProcess.java
License:Open Source License
private ScrollableResults getTransactions(Set<String> childOrgs, Date startDate, Date endDate) { StringBuffer select = new StringBuffer(); select.append("select trx as trx"); select.append(" from " + MaterialTransaction.ENTITY_NAME + " as trx"); select.append(" where trx." + MaterialTransaction.PROPERTY_ORGANIZATION + ".id in (:orgs)"); select.append(" and trx." + MaterialTransaction.PROPERTY_ISCOSTCALCULATED + " = true"); select.append(" and trx." + MaterialTransaction.PROPERTY_TRANSACTIONPROCESSDATE + " >= (:startDate)"); if (endDate != null) { select.append(" and trx." + MaterialTransaction.PROPERTY_TRANSACTIONPROCESSDATE + " < (:endDate)"); }//from ww w. j a v a 2 s . c o m select.append(" order by trx." + MaterialTransaction.PROPERTY_MOVEMENTDATE); Query stockLinesQry = OBDal.getInstance().getSession().createQuery(select.toString()); stockLinesQry.setParameterList("orgs", childOrgs); stockLinesQry.setTimestamp("startDate", startDate); if (endDate != null) { stockLinesQry.setTimestamp("endDate", endDate); } stockLinesQry.setFetchSize(1000); ScrollableResults stockLines = stockLinesQry.scroll(ScrollMode.FORWARD_ONLY); return stockLines; }
From source file:org.openbravo.costing.InventoryAmountUpdateProcess.java
License:Open Source License
private ScrollableResults getStockLines(Set<String> childOrgs, Date date, Product product, Warehouse warehouse, boolean backdatedTransactionsFixed) { StringBuffer select = new StringBuffer(); StringBuffer subSelect = new StringBuffer(); select.append("select trx." + MaterialTransaction.PROPERTY_ATTRIBUTESETVALUE + ".id"); select.append(", trx." + MaterialTransaction.PROPERTY_UOM + ".id"); select.append(", trx." + MaterialTransaction.PROPERTY_ORDERUOM + ".id"); select.append(", trx." + MaterialTransaction.PROPERTY_STORAGEBIN + ".id"); select.append(", loc." + Locator.PROPERTY_WAREHOUSE + ".id"); select.append(", sum(trx." + MaterialTransaction.PROPERTY_MOVEMENTQUANTITY + ")"); select.append(", sum(trx." + MaterialTransaction.PROPERTY_ORDERQUANTITY + ")"); select.append(" from " + MaterialTransaction.ENTITY_NAME + " as trx"); select.append(" join trx." + MaterialTransaction.PROPERTY_STORAGEBIN + " as loc"); select.append(" where trx." + MaterialTransaction.PROPERTY_ORGANIZATION + ".id in (:orgs)"); if (date != null) { if (backdatedTransactionsFixed) { select.append(" and trx." + MaterialTransaction.PROPERTY_MOVEMENTDATE + " <= :date"); } else {// w w w . j a v a2s. co m subSelect.append("select min(trx." + MaterialTransaction.PROPERTY_TRANSACTIONPROCESSDATE + ")"); subSelect.append(" from " + MaterialTransaction.ENTITY_NAME + " as trx"); subSelect.append(" join trx." + MaterialTransaction.PROPERTY_STORAGEBIN + " as locator"); subSelect.append(" where trx." + MaterialTransaction.PROPERTY_PRODUCT + ".id = :product"); subSelect.append(" and trx." + MaterialTransaction.PROPERTY_MOVEMENTDATE + " > :date"); // Include only transactions that have its cost calculated subSelect.append(" and trx." + MaterialTransaction.PROPERTY_ISCOSTCALCULATED + " = true"); if (warehouse != null) { subSelect.append(" and locator." + Locator.PROPERTY_WAREHOUSE + ".id = :warehouse"); } subSelect.append(" and trx." + MaterialTransaction.PROPERTY_ORGANIZATION + ".id in (:orgs)"); Query trxsubQry = OBDal.getInstance().getSession().createQuery(subSelect.toString()); trxsubQry.setParameter("date", date); trxsubQry.setParameter("product", product.getId()); if (warehouse != null) { trxsubQry.setParameter("warehouse", warehouse.getId()); } trxsubQry.setParameterList("orgs", childOrgs); Object trxprocessDate = trxsubQry.uniqueResult(); if (trxprocessDate != null) { date = (Date) trxprocessDate; select.append(" and trx." + MaterialTransaction.PROPERTY_TRANSACTIONPROCESSDATE + " < :date"); } else { select.append(" and trx." + MaterialTransaction.PROPERTY_MOVEMENTDATE + " <= :date"); } } } if (warehouse != null) { select.append(" and loc." + Locator.PROPERTY_WAREHOUSE + " = :warehouse"); } select.append(" and trx." + MaterialTransaction.PROPERTY_PRODUCT + " = :product"); select.append(" group by trx." + MaterialTransaction.PROPERTY_ATTRIBUTESETVALUE + ".id"); select.append(", trx." + MaterialTransaction.PROPERTY_UOM + ".id"); select.append(", trx." + MaterialTransaction.PROPERTY_ORDERUOM + ".id"); select.append(", trx." + MaterialTransaction.PROPERTY_STORAGEBIN + ".id"); select.append(", loc." + Locator.PROPERTY_WAREHOUSE + ".id"); select.append(" having "); select.append(" sum(trx." + MaterialTransaction.PROPERTY_MOVEMENTQUANTITY + ") <> 0"); select.append(" order by loc." + Locator.PROPERTY_WAREHOUSE + ".id"); select.append(", trx." + MaterialTransaction.PROPERTY_STORAGEBIN + ".id"); select.append(", trx." + MaterialTransaction.PROPERTY_ATTRIBUTESETVALUE + ".id"); select.append(", trx." + MaterialTransaction.PROPERTY_UOM + ".id"); select.append(", trx." + MaterialTransaction.PROPERTY_ORDERUOM + ".id"); Query stockLinesQry = OBDal.getInstance().getSession().createQuery(select.toString()); stockLinesQry.setParameterList("orgs", childOrgs); if (date != null) { stockLinesQry.setTimestamp("date", date); } if (warehouse != null) { stockLinesQry.setParameter("warehouse", warehouse); } stockLinesQry.setParameter("product", product); stockLinesQry.setFetchSize(1000); ScrollableResults stockLines = stockLinesQry.scroll(ScrollMode.FORWARD_ONLY); return stockLines; }
From source file:org.openbravo.dal.service.OBQuery.java
License:Open Source License
/** * Creates a Hibernate Query object using the whereclause and extra filters (for readable * organizations etc.).//from www. ja va 2 s . com * * @return a new Hibernate Query object */ public Query createQuery() { final String qryStr = createQueryString(); try { final Query qry = getSession().createQuery(qryStr); setParameters(qry); if (fetchSize > -1) { qry.setFetchSize(fetchSize); } if (firstResult > -1) { qry.setFirstResult(firstResult); } if (maxResult > -1) { qry.setMaxResults(maxResult); } String queryProfile = null; if (this.getQueryType() != null) { queryProfile = this.getQueryType(); } else if (SessionInfo.getQueryProfile() != null) { queryProfile = SessionInfo.getQueryProfile(); } if (queryProfile != null) { QueryTimeOutUtil.getInstance().setQueryTimeOut(qry, queryProfile); } return qry; } catch (final Exception e) { throw new OBException("Exception when creating query " + qryStr, e); } }
From source file:org.openbravo.financial.ResetAccounting.java
License:Open Source License
@SuppressWarnings("unchecked") public static HashMap<String, Integer> delete(String adClientId, String adOrgId, String adTableId, String recordId, String strdatefrom, String strdateto) throws OBException { if (recordId == null) { recordId = ""; }/* ww w . ja v a 2s.c o m*/ long totalProcess = System.currentTimeMillis(); long start = 0l; long end = 0l; long totalselect = 0l; int deleted = 0; int updated = 0; HashMap<String, Integer> results = new HashMap<String, Integer>(); results.put("deleted", 0); results.put("updated", 0); results.put("totaldeleted", 0); results.put("totalupdated", 0); String client = adClientId; List<String> tables = getTables(adTableId); try { Set<String> orgIds = new OrganizationStructureProvider().getChildTree(adOrgId, true); for (String table : tables) { List<String> docbasetypes = getDocbasetypes(client, table, recordId); String myQuery = "select distinct e.recordID from FinancialMgmtAccountingFact e where e.organization.id in (:orgIds) and e.client.id = :clientId and e.table.id = :tableId"; if (recordId != null && !"".equals(recordId)) { myQuery = myQuery + " and e.recordID = :recordId "; } for (String dbt : docbasetypes) { List<Date[]> periods = new ArrayList<Date[]>(); // organizationPeriod: hashmap with organizations allow period control and their open // periods Map<String, List<Date[]>> organizationPeriod = new HashMap<String, List<Date[]>>(); // organizationPeriodControl: hashmap with organizations and their organization allow // period control associated Map<String, String> organizationPeriodControl = new HashMap<String, String>(); String calendarId = getCalendarId(adOrgId); Iterator<String> iterator = orgIds.iterator(); while (iterator.hasNext()) { String organization = iterator.next(); String myQuery1 = "select p.id from Organization p where ad_org_getperiodcontrolallow(:organization)=p.id"; Query query1 = OBDal.getInstance().getSession().createQuery(myQuery1); query1.setString("organization", organization); query1.setMaxResults(1); if (query1.uniqueResult() != null) { String orgperiodcontrol = query1.uniqueResult().toString(); organizationPeriodControl.put(organization, orgperiodcontrol); if (!organizationPeriod.keySet().contains(orgperiodcontrol)) { periods = getPeriodsDates(getOpenPeriods(client, dbt, orgIds, calendarId, table, recordId, strdatefrom, strdateto, orgperiodcontrol)); organizationPeriod.put(orgperiodcontrol, periods); } } } int docUpdated = 0; int docDeleted = 0; for (String organization : orgIds) { String orgAllow = organizationPeriodControl.get(organization); periods = organizationPeriod.get(orgAllow); for (Date[] p : periods) { StringBuffer consDate = new StringBuffer(); consDate.append(" and e.documentCategory = :dbt"); consDate.append(" and e.organization.id = :organization"); consDate.append(" and e.accountingDate >= :dateFrom and e.accountingDate <= :dateTo"); String exceptionsSql = myQuery + consDate.toString(); consDate.append( " and not exists (select a from FinancialMgmtAccountingFact a where a.recordID = e.recordID and a.table.id = e.table.id and (a.accountingDate < :dateFrom or a.accountingDate > :dateTo))"); final Query query = OBDal.getInstance().getSession() .createQuery(myQuery + consDate.toString()); if (recordId != null && !"".equals(recordId)) { query.setString("recordId", recordId); } query.setParameterList("orgIds", orgIds); query.setString("clientId", client); query.setString("dbt", dbt); query.setString("tableId", table); query.setDate("dateFrom", p[0]); query.setDate("dateTo", p[1]); query.setString("organization", organization); if (recordId != null && !"".equals(recordId)) { query.setMaxResults(1); } else { query.setFetchSize(FETCH_SIZE); } start = System.currentTimeMillis(); List<String> transactions = query.list(); end = System.currentTimeMillis(); totalselect = totalselect + end - start; while (transactions.size() > 0) { HashMap<String, Integer> partial = delete(transactions, table, client); deleted = deleted + partial.get("deleted"); updated = updated + partial.get("updated"); docUpdated = docUpdated + partial.get("updated"); docDeleted = docDeleted + partial.get("deleted"); start = System.currentTimeMillis(); transactions = query.list(); end = System.currentTimeMillis(); totalselect = totalselect + end - start; } // Documents with postings in different periods are treated separately to validate // all // dates are within an open period HashMap<String, Integer> partial = treatExceptions(exceptionsSql, recordId, table, orgIds, client, p[0], p[1], calendarId, strdatefrom, strdateto, dbt, orgAllow, organization); deleted = deleted + partial.get("deleted"); updated = updated + partial.get("updated"); docUpdated = docUpdated + partial.get("updated"); docDeleted = docDeleted + partial.get("deleted"); } } log4j.debug("docBaseType: " + dbt); log4j.debug("updated: " + docUpdated); log4j.debug("deleted: " + docDeleted); } } } catch (OBException e) { throw e; } catch (Exception e) { throw new OBException("Delete failed", e); } results.put("deleted", deleted); results.put("updated", updated); log4j.debug("total totalProcess (milies): " + (System.currentTimeMillis() - totalProcess)); if (recordId != null && !"".equals(recordId) && deleted == 0 && updated == 0) { if (recordId != null && !"".equals(recordId) && adTableId != null && !"".equals(adTableId)) { // If record exists but there is no entry in fact table then unpost record try { OBContext.setAdminMode(false); Table table = OBDal.getInstance().get(Table.class, adTableId); OBCriteria<AccountingFact> obc = OBDal.getInstance().createCriteria(AccountingFact.class); obc.setFilterOnReadableClients(false); obc.setFilterOnReadableOrganization(false); obc.setFilterOnActive(false); obc.add(Restrictions.eq(AccountingFact.PROPERTY_RECORDID, recordId)); obc.add(Restrictions.eq(AccountingFact.PROPERTY_TABLE, table)); if (obc.list().size() == 0) { String tableName = table.getDBTableName(); String tableIdName = table.getDBTableName() + "_Id"; String strUpdate = "update " + tableName + " set posted='N', processing='N' where (posted<>'N' or posted is null or processing='N') and " + tableIdName + " = :recordID "; final Query update = OBDal.getInstance().getSession().createSQLQuery(strUpdate); update.setParameter("recordID", recordId); updated = update.executeUpdate(); return results; } } finally { OBContext.restorePreviousMode(); } } throw new OBException("@PeriodClosedForUnPosting@"); } return results; }
From source file:org.openbravo.service.json.DataEntityQueryService.java
License:Open Source License
/** * @return a result which can be scrolled forward only and the results are not cached */// ww w . ja v a 2s.com public ScrollableResults scroll() { final Query qry = buildOBQuery().createQuery(); qry.setFetchSize(1000); qry.setCacheable(false); return qry.scroll(ScrollMode.FORWARD_ONLY); }