List of usage examples for org.hibernate ScrollableResults get
Object[] get();
From source file:org.openbravo.erpCommon.utility.WindowTree.java
License:Open Source License
private List<WindowTreeData> applyWhereClause(List<WindowTreeData> subList, String strTabId) { String entityName = null, hqlWhereClause = null; try {//from ww w. j a v a2 s . c o m OBContext.setAdminMode(); Tab tabData = OBDal.getInstance().get(org.openbravo.model.ad.ui.Tab.class, strTabId); if (tabData != null) { entityName = tabData.getTable().getName(); hqlWhereClause = tabData.getHqlwhereclause(); } } catch (Exception e) { log4j.error("Exception while retrieving hqlWhereClause " + e); } finally { OBContext.restorePreviousMode(); } List<WindowTreeData> newSubList = new ArrayList<WindowTreeData>(); if (hqlWhereClause != null && !hqlWhereClause.trim().isEmpty()) { hqlWhereClause = hqlWhereClause.replaceAll("\\be.", ""); OBQuery<BaseOBObject> entityResults = OBDal.getInstance().createQuery("" + entityName + "", hqlWhereClause); if (nodeIdList == null) { nodeIdList = new ArrayList<String>(); } if (nodeIdList.size() == 0 && nodeIdList.size() != entityResults.count()) { ScrollableResults entityData = entityResults.scroll(ScrollMode.FORWARD_ONLY); int clearEachLoops = 100; int i = 0; try { while (entityData.next()) { i++; BaseOBObject entity = (BaseOBObject) entityData.get()[0]; if (entity.getId() != null) { nodeIdList.add(entity.getId().toString()); } if (i % clearEachLoops == 0) { OBDal.getInstance().getSession().clear(); } } } finally { entityData.close(); } } for (WindowTreeData elem : subList) { if (nodeIdList.contains(elem.nodeId)) { newSubList.add(elem); } } } else { newSubList = subList; } return newSubList; }
From source file:org.openbravo.event.GLJournalEventHandler.java
License:Open Source License
public void onUpdate(@Observes EntityUpdateEvent event) { if (!isValidEvent(event)) { return;//from w w w . jav a 2 s . c o m } final GLJournal glj = (GLJournal) event.getTargetInstance(); // Update GLJournalLine with updated Currency and Currency Rate. final Entity gljournal = ModelProvider.getInstance().getEntity(GLJournal.ENTITY_NAME); final Property currencyProperty = gljournal.getProperty(GLJournal.PROPERTY_CURRENCY); final Property currencyRate = gljournal.getProperty(GLJournal.PROPERTY_RATE); if (!event.getCurrentState(currencyProperty).equals(event.getPreviousState(currencyProperty)) || !event.getCurrentState(currencyRate).equals(event.getPreviousState(currencyRate))) { OBCriteria<GLJournalLine> gljournallineCriteria = OBDal.getInstance() .createCriteria(GLJournalLine.class); gljournallineCriteria.add(Restrictions.eq(GLJournalLine.PROPERTY_JOURNALENTRY, glj)); ScrollableResults scrollLines = gljournallineCriteria.scroll(ScrollMode.FORWARD_ONLY); try { if (gljournallineCriteria.count() > 0) { int i = 0; while (scrollLines.next()) { final GLJournalLine journalLine = (GLJournalLine) scrollLines.get()[0]; if (!glj.getCurrency().getId().equals(journalLine.getCurrency().getId())) { journalLine.setCurrency(glj.getCurrency()); OBDal.getInstance().save(journalLine); } if (!glj.getRate().equals(journalLine.getRate())) { journalLine.setRate(glj.getRate()); OBDal.getInstance().save(journalLine); } i++; if (i % 100 == 0) { OBDal.getInstance().flush(); OBDal.getInstance().getSession().clear(); } } } } finally { scrollLines.close(); } } }
From source file:org.openbravo.event.RoleEventHandler.java
License:Open Source License
private List<RoleOrganization> getRoleOrganizationList(Role role) throws Exception { List<RoleOrganization> roleOrganizationList = new ArrayList<RoleOrganization>(); // Client or System level: Only * [isOrgAdmin=N] if (StringUtils.equals(role.getUserLevel(), " C") || StringUtils.equals(role.getUserLevel(), "S")) { roleOrganizationList//www . j ava 2 s.c om .add(getRoleOrganization(role, OBDal.getInstance().get(Organization.class, "0"), false)); logger.debug("Added organization * to role " + role.getName()); } // Client/Organization level: * [isOrgAdmin=N], other Orgs (but *) [isOrgAdmin=Y] else if (StringUtils.equals(role.getUserLevel(), " CO")) { roleOrganizationList .add(getRoleOrganization(role, OBDal.getInstance().get(Organization.class, "0"), false)); logger.debug("Added organization * to role " + role.getName()); OBCriteria<Organization> criteria = OBDal.getInstance().createCriteria(Organization.class); criteria.add(Restrictions.eq(Organization.PROPERTY_CLIENT, role.getClient())); criteria.add(Restrictions.ne(Organization.PROPERTY_ID, "0")); ScrollableResults scroll = criteria.scroll(ScrollMode.FORWARD_ONLY); try { while (scroll.next()) { final Organization organization = (Organization) scroll.get()[0]; roleOrganizationList.add(getRoleOrganization(role, organization, true)); logger.debug("Added organization " + organization.getName() + " to role " + role.getName()); } } finally { scroll.close(); } } // Organization level: Orgs (but *) [isOrgAdmin=Y] else if (StringUtils.equals(role.getUserLevel(), " O")) { OBCriteria<Organization> criteria = OBDal.getInstance().createCriteria(Organization.class); criteria.add(Restrictions.eq(Organization.PROPERTY_CLIENT, role.getClient())); ScrollableResults scroll = criteria.scroll(ScrollMode.FORWARD_ONLY); try { while (scroll.next()) { final Organization organization = (Organization) scroll.get()[0]; roleOrganizationList.add(getRoleOrganization(role, organization, true)); logger.debug("Added organization " + organization.getName() + " to role " + role.getName()); } } finally { scroll.close(); } } return roleOrganizationList; }
From source file:org.openbravo.service.datasource.ADTreeDatasourceService.java
License:Open Source License
/** * /*from w w w . j a v a2s. c o m*/ * @param parentId * id of the node whose children are to be retrieved * @param hqlWhereClause * hql where clase of the tab/selector * @param hqlWhereClauseRootNodes * hql where clause that define what nodes are roots * @return A JSONArray containing all the children of the given node * @throws JSONException * @throws TooManyTreeNodesException * if the number of returned nodes were to be too high */ @Override protected JSONArray fetchNodeChildren(Map<String, String> parameters, Map<String, Object> datasourceParameters, String parentId, String hqlWhereClause, String hqlWhereClauseRootNodes) throws JSONException, TooManyTreeNodesException { String tabId = parameters.get("tabId"); String treeReferenceId = parameters.get("treeReferenceId"); Tab tab = null; JSONArray selectedProperties = null; if (tabId != null) { tab = OBDal.getInstance().get(Tab.class, tabId); String selectedPropertiesStr = parameters.get("_selectedProperties"); selectedProperties = new JSONArray(selectedPropertiesStr); } else if (treeReferenceId != null) { ReferencedTree treeReference = OBDal.getInstance().get(ReferencedTree.class, treeReferenceId); treeReference.getADReferencedTreeFieldList(); selectedProperties = new JSONArray(); for (ReferencedTreeField treeField : treeReference.getADReferencedTreeFieldList()) { selectedProperties.put(treeField.getProperty()); } } else { logger.error( "A request to the TreeDatasourceService must include the tabId or the treeReferenceId parameter"); return new JSONArray(); } Tree tree = (Tree) datasourceParameters.get("tree"); JSONArray responseData = new JSONArray(); Entity entity = ModelProvider.getInstance().getEntityByTableId(tree.getTable().getId()); final DataToJsonConverter toJsonConverter = OBProvider.getInstance().get(DataToJsonConverter.class); // Joins the ADTreeNode with the referenced table StringBuilder joinClause = new StringBuilder(); joinClause.append(" as tn "); joinClause.append(" , " + entity.getName() + " as e "); joinClause.append(" where tn.node = e.id "); if (hqlWhereClause != null) { joinClause.append(" and (" + hqlWhereClause + ")"); } joinClause.append(" and tn.tree.id = '" + tree.getId() + "' "); if (hqlWhereClauseRootNodes == null && tab != null && tab.getTabLevel() > 0) { // Add the criteria to filter only the records that belong to the record selected in the // parent tab Tab parentTab = KernelUtils.getInstance().getParentTab(tab); String parentPropertyName = ApplicationUtils.getParentProperty(tab, parentTab); if (parentPropertyName != null) { JSONArray criteria = (JSONArray) JsonUtils.buildCriteria(parameters).get("criteria"); String parentRecordId = getParentRecordIdFromCriteria(criteria, parentPropertyName); if (parentRecordId != null) { joinClause.append(" and e." + parentPropertyName + ".id = '" + parentRecordId + "' "); } } } if (hqlWhereClauseRootNodes != null) { joinClause.append(" and (" + hqlWhereClauseRootNodes + ") "); } else { if (ROOT_NODE_CLIENT.equals(parentId)) { if (AD_ORG_TABLE_ID.equals(tree.getTable().getId())) { // The ad_org table needs a special treatment, since is the only table tree that has an // actual node ('*' organization) with node_id = ROOT_NODE_DB // In this table the root nodes have the parent_id property set to null joinClause.append(" and tn.reportSet is null"); } else { // Other ad_tree nodes can have either ROOT_NODE_DB or null as parent_id joinClause.append(" and (tn.reportSet = '" + ROOT_NODE_DB + "' or tn.reportSet is null)"); } } else { joinClause.append(" and tn.reportSet = '" + parentId + "' "); } } joinClause.append(" order by tn.sequenceNumber "); // Selects the relevant properties from ADTreeNode and all the properties from the referenced // table String selectClause = " tn.id as treeNodeId, tn.reportSet as parentId, tn.sequenceNumber as seqNo, tn.node as nodeId, e as entity"; OBQuery<BaseOBObject> obq = OBDal.getInstance().createQuery("ADTreeNode", joinClause.toString()); obq.setFilterOnActive(false); obq.setSelectClause(selectClause); obq.setFilterOnReadableOrganization(false); int nResults = obq.count(); OBContext context = OBContext.getOBContext(); int nMaxResults = -1; try { nMaxResults = Integer.parseInt( Preferences.getPreferenceValue("TreeDatasourceFetchLimit", false, context.getCurrentClient(), context.getCurrentOrganization(), context.getUser(), context.getRole(), null)); } catch (Exception e) { nMaxResults = 1000; } if (nResults > nMaxResults) { throw new TooManyTreeNodesException(); } boolean fetchRoot = ROOT_NODE_CLIENT.equals(parentId); int PARENT_ID = 1; int SEQNO = 2; int NODE_ID = 3; int ENTITY = 4; int cont = 0; ScrollableResults scrollNodes = obq.createQuery().scroll(ScrollMode.FORWARD_ONLY); try { while (scrollNodes.next()) { Object[] node = scrollNodes.get(); JSONObject value = null; BaseOBObject bob = (BaseOBObject) node[ENTITY]; try { value = toJsonConverter.toJsonObject(bob, DataResolvingMode.FULL); value.put("nodeId", bob.getId().toString()); if (fetchRoot) { value.put("parentId", ROOT_NODE_CLIENT); } else { value.put("parentId", node[PARENT_ID]); } addNodeCommonAttributes(entity, bob, value); value.put("seqno", node[SEQNO]); value.put("_hasChildren", (this.nodeHasChildren(entity, (String) node[NODE_ID], hqlWhereClause)) ? true : false); } catch (JSONException e) { logger.error("Error while constructing JSON reponse", e); } responseData.put(value); if ((cont % 100) == 0) { OBDal.getInstance().flush(); OBDal.getInstance().getSession().clear(); } cont++; } } finally { scrollNodes.close(); } return responseData; }
From source file:org.openbravo.service.datasource.LinkToParentTreeDatasourceService.java
License:Open Source License
/** * // w w w. j a v a2 s.c om * @param parameters * @param parentId * id of the node whose children are to be retrieved * @param hqlWhereClause * hql where clase of the tab/selector * @param hqlWhereClauseRootNodes * hql where clause that define what nodes are roots * @throws JSONException * @throws TooManyTreeNodesException * if the number of returned nodes were to be too high */ @Override protected JSONArray fetchNodeChildren(Map<String, String> parameters, Map<String, Object> datasourceParameters, String parentId, String hqlWhereClause, String hqlWhereClauseRootNodes) throws JSONException, TooManyTreeNodesException { boolean fetchRoot = ROOT_NODE_CLIENT.equals(parentId); String tabId = parameters.get("tabId"); String treeReferenceId = parameters.get("treeReferenceId"); Tab tab = null; Table table = null; TableTree tableTree = null; if (tabId != null) { tab = OBDal.getInstance().get(Tab.class, tabId); table = tab.getTable(); tableTree = tab.getTableTree(); } else if (treeReferenceId != null) { ReferencedTree treeReference = OBDal.getInstance().get(ReferencedTree.class, treeReferenceId); table = treeReference.getTable(); tableTree = treeReference.getTableTreeCategory(); } else { logger.error( "A request to the TreeDatasourceService must include the tabId or the treeReferenceId parameter"); return new JSONArray(); } Entity entity = ModelProvider.getInstance().getEntityByTableId(table.getId()); Property linkToParentProperty = getLinkToParentProperty(tableTree); Property nodeIdProperty = getNodeIdProperty(tableTree); boolean isMultiParentTree = tableTree.isHasMultiparentNodes(); StringBuilder whereClause = new StringBuilder(); final List<Object> queryParameters = new ArrayList<Object>(); whereClause.append(" as e where "); String actualParentId = new String(parentId); if (isMultiParentTree) { // The ids of multi parent trees are formed by the concatenation of the ids of its parents, // beginning with its root // node if (parentId.contains(ID_SEPARATOR)) { actualParentId = parentId.substring(parentId.lastIndexOf(ID_SEPARATOR) + 1); } } // check if we can avoid to apply the where clause when fetching the child nodes boolean allowNotApplyingWhereClauseToChildren = !tableTree.isApplyWhereClauseToChildNodes(); if ((fetchRoot || !allowNotApplyingWhereClauseToChildren) && hqlWhereClause != null) { // Include the hql where clause for all root nodes and for child nodes only if it is required whereClause.append(hqlWhereClause + " and "); } if (hqlWhereClauseRootNodes != null && fetchRoot) { // If we are fetching the root nodes and there is a defined hqlWhereClauseRootNodes, apply it whereClause.append(" " + hqlWhereClauseRootNodes + " "); } else { whereClause.append(" e." + linkToParentProperty.getName()); if (fetchRoot) { whereClause.append(" is null "); } else { if (!linkToParentProperty.isPrimitive()) { whereClause.append(".id"); } whereClause.append(" = ? "); queryParameters.add(actualParentId); } if (tab != null && tab.getTabLevel() > 0) { // only try to add the parent tab criteria when the tab is not the header addParentTabCriteria(whereClause, tab, parameters, queryParameters); } } final OBQuery<BaseOBObject> query = OBDal.getInstance().createQuery(entity.getName(), whereClause.toString()); query.setParameters(queryParameters); final DataToJsonConverter toJsonConverter = OBProvider.getInstance().get(DataToJsonConverter.class); JSONArray responseData = new JSONArray(); // Check if the number of results to be returned is not higher than the defined limit int nResults = query.count(); OBContext context = OBContext.getOBContext(); int nMaxResults = -1; try { nMaxResults = Integer.parseInt( Preferences.getPreferenceValue("TreeDatasourceFetchLimit", false, context.getCurrentClient(), context.getCurrentOrganization(), context.getUser(), context.getRole(), null)); } catch (Exception e) { nMaxResults = 1000; } if (nResults > nMaxResults) { throw new TooManyTreeNodesException(); } int count = 0; final ScrollableResults scrollableResults = query.scroll(ScrollMode.FORWARD_ONLY); try { while (scrollableResults.next()) { BaseOBObject bob = (BaseOBObject) scrollableResults.get()[0]; final JSONObject json = toJsonConverter.toJsonObject(bob, DataResolvingMode.FULL); if (fetchRoot) { json.put("parentId", ROOT_NODE_CLIENT); } else { json.put("parentId", parentId); } Object nodeId = bob.get(nodeIdProperty.getName()); String nodeIdStr = null; if (nodeId instanceof String) { nodeIdStr = (String) nodeId; } else if (nodeId instanceof BaseOBObject) { nodeIdStr = ((BaseOBObject) nodeId).getId().toString(); } Object parentNodeId = bob.get(linkToParentProperty.getName()); String parentNodeIdStr = null; if (parentNodeId instanceof String) { parentNodeIdStr = (String) parentNodeId; } else if (parentNodeId instanceof BaseOBObject) { parentNodeIdStr = ((BaseOBObject) parentNodeId).getId().toString(); } if (isMultiParentTree) { json.put("nodeId", parentNodeIdStr + ID_SEPARATOR + nodeIdStr); } else { json.put("nodeId", nodeIdStr); } addNodeCommonAttributes(entity, bob, json); json.put("_hasChildren", (this.nodeHasChildren(entity, linkToParentProperty, nodeIdProperty, bob, hqlWhereClause)) ? true : false); responseData.put(json); count++; if (count % 100 == 0) { OBDal.getInstance().getSession().clear(); } } } finally { scrollableResults.close(); } return responseData; }
From source file:org.openbravo.service.datasource.LinkToParentTreeDatasourceService.java
License:Open Source License
protected List<JSONObject> fetchParentsOfNode(Map<String, String> parameters, String parentId, String hqlWhereClause, String hqlWhereClauseRootNodes) throws TooManyTreeNodesException { List<JSONObject> parentList = new ArrayList<JSONObject>(); String tabId = parameters.get("tabId"); String treeReferenceId = parameters.get("treeReferenceId"); Tab tab = null;// w w w .jav a 2 s . c o m Table table = null; TableTree tableTree = null; if (tabId != null) { tab = OBDal.getInstance().get(Tab.class, tabId); table = tab.getTable(); tableTree = tab.getTableTree(); } else if (treeReferenceId != null) { ReferencedTree treeReference = OBDal.getInstance().get(ReferencedTree.class, treeReferenceId); table = treeReference.getTable(); tableTree = treeReference.getTableTreeCategory(); } else { logger.error( "A request to the TreeDatasourceService must include the tabId or the treeReferenceId parameter"); return new ArrayList<JSONObject>(); } Entity entity = ModelProvider.getInstance().getEntityByTableId(table.getId()); Property linkToParentProperty = getLinkToParentProperty(tableTree); Property nodeIdProperty = getNodeIdProperty(tableTree); StringBuilder whereClause = new StringBuilder(); whereClause.append(" as e where "); whereClause.append(" e." + nodeIdProperty.getName()); if (!nodeIdProperty.isPrimitive()) { whereClause.append(".id"); } whereClause.append(" = ? "); final OBQuery<BaseOBObject> query = OBDal.getInstance().createQuery(entity.getName(), whereClause.toString()); final List<Object> queryParameters = new ArrayList<Object>(); queryParameters.add(parentId); query.setParameters(queryParameters); final DataToJsonConverter toJsonConverter = OBProvider.getInstance().get(DataToJsonConverter.class); // Check if the number of results to be returned is not higher than the defined limit int nResults = query.count(); OBContext context = OBContext.getOBContext(); int nMaxResults = -1; try { nMaxResults = Integer.parseInt( Preferences.getPreferenceValue("TreeDatasourceFetchLimit", false, context.getCurrentClient(), context.getCurrentOrganization(), context.getUser(), context.getRole(), null)); } catch (Exception e) { nMaxResults = 100; } if (nResults > nMaxResults) { throw new TooManyTreeNodesException(); } int count = 0; final ScrollableResults scrollableResults = query.scroll(ScrollMode.FORWARD_ONLY); try { while (scrollableResults.next()) { BaseOBObject bob = (BaseOBObject) scrollableResults.get()[0]; final JSONObject json = toJsonConverter.toJsonObject(bob, DataResolvingMode.FULL); Object nodeId = bob.get(nodeIdProperty.getName()); String nodeIdStr = null; if (nodeId instanceof String) { nodeIdStr = (String) nodeId; } else if (nodeId instanceof BaseOBObject) { nodeIdStr = ((BaseOBObject) nodeId).getId().toString(); } Object parentNodeId = bob.get(linkToParentProperty.getName()); String parentNodeIdStr = null; if (parentNodeId instanceof String) { parentNodeIdStr = (String) parentNodeId; } else if (parentNodeId instanceof BaseOBObject) { parentNodeIdStr = ((BaseOBObject) parentNodeId).getId().toString(); } try { json.put("nodeId", nodeIdStr); if (parentNodeIdStr == null) { json.put("parentId", ROOT_NODE_CLIENT); } else { json.put("parentId", parentNodeIdStr); } } catch (JSONException e) { logger.error("Error on tree datasource", e); } parentList.add(json); count++; if (count % 100 == 0) { OBDal.getInstance().getSession().clear(); } } } finally { scrollableResults.close(); } return parentList; }
From source file:org.openbravo.service.json.DefaultJsonDataService.java
License:Open Source License
public void fetch(Map<String, String> parameters, QueryResultWriter writer) { long t = System.currentTimeMillis(); doPreAction(parameters, "", DataSourceAction.FETCH); final DataEntityQueryService queryService = createSetQueryService(parameters, false); String selectedProperties = parameters.get(JsonConstants.SELECTEDPROPERTIES_PARAMETER); final DataToJsonConverter toJsonConverter = OBProvider.getInstance().get(DataToJsonConverter.class); toJsonConverter.setAdditionalProperties(JsonUtils.getAdditionalProperties(parameters)); // Convert to Json only the properties specified in the request. If no properties are specified, // all of them will be converted to Json toJsonConverter.setSelectedProperties(selectedProperties); final ScrollableResults scrollableResults = queryService.scroll(); try {/*from w ww . ja va 2 s.c om*/ int i = 0; while (scrollableResults.next()) { final Object result = scrollableResults.get()[0]; final JSONObject json = toJsonConverter.toJsonObject((BaseOBObject) result, DataResolvingMode.FULL); try { doPostFetch(parameters, json); } catch (JSONException e) { throw new OBException(e); } writer.write(json); i++; // Clear session every 1000 records to prevent huge memory consumption in case of big loops if (i % 1000 == 0) { OBDal.getInstance().getSession().clear(); log.debug("clearing in record " + i + " elapsed time " + (System.currentTimeMillis() - t)); } } } finally { scrollableResults.close(); } log.debug("Fetch took " + (System.currentTimeMillis() - t) + " ms"); }
From source file:org.openbravo.test.dal.DalPerformanceExampleTest.java
License:Open Source License
/** * Scrollable results// www.ja va2 s .c om */ @Test public void testSimpleScrollQuery() { setTestUserContext(); final OBCriteria<Product> productCriteria = OBDal.getInstance().createCriteria(Product.class); // 1000 is normally a good fetch size productCriteria.setFetchSize(1000); final ScrollableResults productScroller1 = productCriteria.scroll(ScrollMode.FORWARD_ONLY); int i = 0; while (productScroller1.next()) { final Product product = (Product) productScroller1.get()[0]; System.err.println(product.getId()); // clear the session every 100 records if ((i % 100) == 0) { OBDal.getInstance().getSession().clear(); } i++; } i = 0; final OBQuery<Product> productQuery = OBDal.getInstance().createQuery(Product.class, ""); // 1000 is normally a good fetch size productQuery.setFetchSize(1000); final ScrollableResults productScroller2 = productQuery.scroll(ScrollMode.FORWARD_ONLY); while (productScroller2.next()) { final Product product = (Product) productScroller2.get()[0]; System.err.println(product.getId()); // clear the session every 100 records if ((i % 100) == 0) { OBDal.getInstance().getSession().clear(); } i++; } }
From source file:org.openbravo.test.dal.DalPerformanceExampleTest.java
License:Open Source License
/** * Show explicit joining of referenced objects */// ww w. ja va2 s.c o m @Test public void testJoinReferencedObjects() { setTestUserContext(); { int i = 0; final OBQuery<BusinessPartner> bpQuery = OBDal.getInstance().createQuery(BusinessPartner.class, ""); bpQuery.setMaxResult(1000); final ScrollableResults scroller = bpQuery.scroll(ScrollMode.FORWARD_ONLY); while (scroller.next()) { final BusinessPartner bp = (BusinessPartner) scroller.get()[0]; // this will load the category object with a separate query System.err.println(bp.getBusinessPartnerCategory().getIdentifier()); // clear the session every 100 records if ((i % 10) == 0) { OBDal.getInstance().getSession().clear(); } i++; } } // start with an empty session OBDal.getInstance().getSession().clear(); { int i = 0; // for joining referenced objects we can't use OBQuery, but have to // use a direct Hibernate query object final String queryStr = "from BusinessPartner as bp left join bp.businessPartnerCategory where bp.organization.id " + OBDal.getInstance().getReadableOrganizationsInClause(); final Query qry = OBDal.getInstance().getSession().createQuery(queryStr); qry.setMaxResults(1000); final ScrollableResults scroller = qry.scroll(ScrollMode.FORWARD_ONLY); while (scroller.next()) { final BusinessPartner bp = (BusinessPartner) scroller.get()[0]; // the category is already loaded, so this won't fire a query System.err.println(bp.getBusinessPartnerCategory().getIdentifier()); // clear the session every 100 records if ((i % 100) == 0) { OBDal.getInstance().getSession().clear(); } i++; } } }
From source file:org.openhie.openempi.blocking.basicblockinghp.dao.hibernate.BlockingDaoHibernate.java
License:Open Source License
@SuppressWarnings({ "unchecked", "rawtypes" }) public Record loadRecord(final long recordId, final List<String> fieldNameSet) { final String[] fieldNames = fieldNameSet.toArray(new String[] {}); return (Record) getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) { try { org.hibernate.Criteria criteria = createQueryFromFields(session, fieldNameSet); criteria.add(Restrictions.eq("personId", new Integer((int) recordId))); criteria.setCacheMode(CacheMode.IGNORE); criteria.setFetchSize(10000); ScrollableResults iterator = criteria.scroll(ScrollMode.FORWARD_ONLY); int count = 0; Record record = null;// ww w .j av a2 s.c om while (iterator.next()) { Object[] values = iterator.get(); Person person = populatePersonObject(fieldNames, values); Long recordId = person.getPersonId().longValue(); record = new Record(person); record.setRecordId(recordId); log.trace("Loaded " + count + " records with id " + recordId + " into the cache."); count++; } return record; } catch (Exception e) { log.error("Failed while scrolling through the records: " + e, e); throw new RuntimeException("Failed while scrolling through the records: " + e.getMessage()); } } }); }