use of org.apache.ofbiz.entity.util.EntityFindOptions in project ofbiz-framework by apache.
the class EntityQueryTestSuite method testMaxRows.
/*
* maxRows(): This method sets the maximum number of records to be fetched by the query.
* assert 1: Compared number of records returned by Entity Engine method and by EntityQuery method.
* assert 2: Compared 'testingTypeId' field of first record fetched by Entity Engine method and by EntityQuery method.
* assert 3: Compared 'description' field of first record fetched by Entity Engine method and by EntityQuery method.
*/
public void testMaxRows() throws GenericEntityException {
List<GenericValue> testingTypes = new LinkedList<>();
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "maxRows-1", "description", "Max Row One"));
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "maxRows-2", "description", "Max Row Two"));
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "maxRows-3", "description", "Max Row Three"));
delegator.storeAll(testingTypes);
EntityFindOptions findOptions = new EntityFindOptions();
findOptions.setMaxRows(2);
List<GenericValue> maxRowsByEntityEngine = delegator.findList("TestingType", null, null, UtilMisc.toList("description"), findOptions, false);
List<GenericValue> maxRowsByEntityQuery = EntityQuery.use(delegator).from("TestingType").maxRows(2).orderBy("description").queryList();
assertEquals("maxRows(): Number of records found by both the methods matched", maxRowsByEntityEngine.size(), maxRowsByEntityQuery.size());
assertEquals("maxRows(): Record matched = testingTypeId", maxRowsByEntityEngine.get(0).getString("testingTypeId"), maxRowsByEntityQuery.get(0).getString("testingTypeId"));
assertEquals("maxRows(): Record matched = description", maxRowsByEntityEngine.get(0).getString("description"), maxRowsByEntityQuery.get(0).getString("description"));
}
use of org.apache.ofbiz.entity.util.EntityFindOptions in project ofbiz-framework by apache.
the class EntityQueryTestSuite method testFetchSize.
/*
* fetchSize(): This method sets the fetch size for the records to be fetched from the entity.
* assert 1: Compared number of records returned by Entity Engine method and by EntityQuery method.
* assert 2: Compared 'testingTypeId' field of first record fetched by Entity Engine method and by EntityQuery method.
* assert 3: Compared 'description' field of first record fetched by Entity Engine method and by EntityQuery method.
*/
public void testFetchSize() throws GenericEntityException {
List<GenericValue> testingTypes = new LinkedList<>();
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "fetchSize-1", "description", "Fetch Size One"));
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "fetchSize-2", "description", "Fetch Size Two"));
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "fetchSize-3", "description", "Fetch Size Three"));
delegator.storeAll(testingTypes);
EntityFindOptions findOptions = new EntityFindOptions();
findOptions.setFetchSize(2);
List<GenericValue> fetchSizeByEntityEngine = delegator.findList("TestingType", null, null, UtilMisc.toList("description"), findOptions, false);
List<GenericValue> fetchSizeByEntityQuery = EntityQuery.use(delegator).from("TestingType").fetchSize(2).orderBy("description").queryList();
assertEquals("fetchSize(): Number of records found by both the methods matched", fetchSizeByEntityEngine.size(), fetchSizeByEntityQuery.size());
assertEquals("fetchSize(): Record matched = testingTypeId", fetchSizeByEntityEngine.get(0).getString("testingTypeId"), fetchSizeByEntityQuery.get(0).getString("testingTypeId"));
assertEquals("fetchSize(): Record matched = description", fetchSizeByEntityEngine.get(0).getString("description"), fetchSizeByEntityQuery.get(0).getString("description"));
}
use of org.apache.ofbiz.entity.util.EntityFindOptions in project ofbiz-framework by apache.
the class EntityQueryTestSuite method testDistinctAndSelect.
/*
* distinct(): This method is used to get distinct values of records from entity field. (Note: Distinct method is generally used with select method)
* assert 1: Compared size of the list returned by Entity Engine method and by EntityQuery method.
* assert 2: Compared value of first record of selected 'description' field by both EntityEngine method and EntityQuery method.
* assert 3: Compared 'testingTypeId' field for null which is fetched by EntityQuery method.
*/
public void testDistinctAndSelect() throws GenericEntityException {
List<GenericValue> testingTypes = new LinkedList<>();
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "distinct-1", "description", "Distinct Record"));
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "distinct-2", "description", "Distinct Record"));
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "distinct-3", "description", "Not a Distinct Record"));
delegator.storeAll(testingTypes);
EntityFindOptions findOptions = new EntityFindOptions();
findOptions.setDistinct(true);
List<GenericValue> distinctByEntityEngine = delegator.findList("TestingType", null, UtilMisc.toSet("description"), UtilMisc.toList("description"), findOptions, false);
List<GenericValue> distinctByEntityQuery = EntityQuery.use(delegator).select("description").from("TestingType").distinct().orderBy("description").queryList();
assertEquals("distinct(): Number of records found by EntityEngine method are matching with records found by EntityQuery distinct method", distinctByEntityEngine.size(), distinctByEntityQuery.size());
assertEquals("distinct(): Record matched = description", distinctByEntityEngine.get(0).getString("description"), distinctByEntityQuery.get(0).getString("description"));
assertNull(distinctByEntityQuery.get(0).getString("testingTypeId"));
}
use of org.apache.ofbiz.entity.util.EntityFindOptions in project ofbiz-framework by apache.
the class OrderServices method createAlsoBoughtProductAssocs.
public static Map<String, Object> createAlsoBoughtProductAssocs(DispatchContext dctx, Map<String, ? extends Object> context) {
final Delegator delegator = dctx.getDelegator();
LocalDispatcher dispatcher = dctx.getDispatcher();
// All orders with an entryDate > orderEntryFromDateTime will be processed
Timestamp orderEntryFromDateTime = (Timestamp) context.get("orderEntryFromDateTime");
// If true all orders ever created will be processed and any pre-existing ALSO_BOUGHT ProductAssocs will be expired
boolean processAllOrders = context.get("processAllOrders") == null ? false : (Boolean) context.get("processAllOrders");
if (orderEntryFromDateTime == null && !processAllOrders) {
// No from date supplied, check to see when this service last ran and use the startDateTime
// FIXME: This code is unreliable - the JobSandbox value might have been purged. Use another mechanism to persist orderEntryFromDateTime.
EntityCondition cond = EntityCondition.makeCondition(UtilMisc.toMap("statusId", "SERVICE_FINISHED", "serviceName", "createAlsoBoughtProductAssocs"));
EntityFindOptions efo = new EntityFindOptions();
efo.setMaxRows(1);
try {
GenericValue lastRunJobSandbox = EntityUtil.getFirst(delegator.findList("JobSandbox", cond, null, UtilMisc.toList("startDateTime DESC"), efo, false));
if (lastRunJobSandbox != null) {
orderEntryFromDateTime = lastRunJobSandbox.getTimestamp("startDateTime");
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
if (orderEntryFromDateTime == null) {
// Still null, process all orders
processAllOrders = true;
}
}
if (processAllOrders) {
// Expire any pre-existing ALSO_BOUGHT ProductAssocs in preparation for reprocessing
EntityCondition cond = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("productAssocTypeId", "ALSO_BOUGHT"), EntityCondition.makeConditionDate("fromDate", "thruDate")));
try {
delegator.storeByCondition("ProductAssoc", UtilMisc.toMap("thruDate", UtilDateTime.nowTimestamp()), cond);
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
}
List<EntityExpr> orderCondList = UtilMisc.toList(EntityCondition.makeCondition("orderTypeId", "SALES_ORDER"));
if (!processAllOrders && orderEntryFromDateTime != null) {
orderCondList.add(EntityCondition.makeCondition("entryDate", EntityOperator.GREATER_THAN, orderEntryFromDateTime));
}
final EntityCondition cond = EntityCondition.makeCondition(orderCondList);
List<String> orderIds;
try {
orderIds = TransactionUtil.doNewTransaction(new Callable<List<String>>() {
@Override
public List<String> call() throws Exception {
List<String> orderIds = new LinkedList<>();
EntityQuery eq = EntityQuery.use(delegator).select("orderId").from("OrderHeader").where(cond).orderBy("entryDate ASC");
try (EntityListIterator eli = eq.queryIterator()) {
GenericValue orderHeader;
while ((orderHeader = eli.next()) != null) {
orderIds.add(orderHeader.getString("orderId"));
}
}
return orderIds;
}
}, "getSalesOrderIds", 0, true);
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
for (String orderId : orderIds) {
Map<String, Object> svcIn = new HashMap<>();
svcIn.put("userLogin", context.get("userLogin"));
svcIn.put("orderId", orderId);
try {
Map<String, Object> serviceResult = dispatcher.runSync("createAlsoBoughtProductAssocsForOrder", svcIn);
if (ServiceUtil.isError(serviceResult)) {
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult));
}
} catch (GenericServiceException e) {
Debug.logError(e, module);
}
}
return ServiceUtil.returnSuccess();
}
use of org.apache.ofbiz.entity.util.EntityFindOptions in project ofbiz-framework by apache.
the class GenericDAO method selectListIteratorByCondition.
/* ====================================================================== */
/* ====================================================================== */
/**
* Finds GenericValues by the conditions specified in the EntityCondition object, the the EntityCondition javadoc for more details.
*@param modelEntity The ModelEntity of the Entity as defined in the entity XML file
*@param whereEntityCondition The EntityCondition object that specifies how to constrain this query before any groupings are done (if this is a view entity with group-by aliases)
*@param havingEntityCondition The EntityCondition object that specifies how to constrain this query after any groupings are done (if this is a view entity with group-by aliases)
*@param fieldsToSelect The fields of the named entity to get from the database; if empty or null all fields will be retreived
*@param orderBy The fields of the named entity to order the query by; optionally add a " ASC" for ascending or " DESC" for descending
*@param findOptions An instance of EntityFindOptions that specifies advanced query options. See the EntityFindOptions JavaDoc for more details.
*@return EntityListIterator representing the result of the query: NOTE THAT THIS MUST BE CLOSED WHEN YOU ARE
* DONE WITH IT (preferably in a finally block),
* AND DON'T LEAVE IT OPEN TOO LONG BECAUSE IT WILL MAINTAIN A DATABASE CONNECTION.
*/
public EntityListIterator selectListIteratorByCondition(Delegator delegator, ModelEntity modelEntity, EntityCondition whereEntityCondition, EntityCondition havingEntityCondition, Collection<String> fieldsToSelect, List<String> orderBy, EntityFindOptions findOptions) throws GenericEntityException {
if (modelEntity == null) {
return null;
}
ModelViewEntity modelViewEntity = null;
if (modelEntity instanceof ModelViewEntity) {
modelViewEntity = (ModelViewEntity) modelEntity;
}
// if no find options passed, use default
if (findOptions == null)
findOptions = new EntityFindOptions();
boolean verboseOn = Debug.verboseOn();
if (verboseOn) {
// put this inside an if statement so that we don't have to generate the string when not used...
if (Debug.verboseOn())
Debug.logVerbose("Doing selectListIteratorByCondition with whereEntityCondition: " + whereEntityCondition, module);
}
// make two ArrayLists of fields, one for fields to select and the other for where clause fields (to find by)
List<ModelField> selectFields = new LinkedList<ModelField>();
if (UtilValidate.isNotEmpty(fieldsToSelect)) {
Set<String> tempKeys = new HashSet<String>();
tempKeys.addAll(fieldsToSelect);
Set<String> fieldSetsToInclude = new HashSet<String>();
Set<String> addedFields = new HashSet<String>();
for (String fieldToSelect : fieldsToSelect) {
if (tempKeys.contains(fieldToSelect)) {
ModelField curField = modelEntity.getField(fieldToSelect);
if (curField != null) {
fieldSetsToInclude.add(curField.getFieldSet());
selectFields.add(curField);
tempKeys.remove(fieldToSelect);
addedFields.add(fieldToSelect);
}
}
}
if (tempKeys.size() > 0) {
throw new GenericModelException("In selectListIteratorByCondition invalid field names specified: " + tempKeys.toString());
}
fieldSetsToInclude.remove("");
if (verboseOn) {
Debug.logInfo("[" + modelEntity.getEntityName() + "]: field-sets to include: " + fieldSetsToInclude, module);
}
if (UtilValidate.isNotEmpty(fieldSetsToInclude)) {
Iterator<ModelField> fieldIter = modelEntity.getFieldsIterator();
Set<String> extraFields = new HashSet<String>();
Set<String> reasonSets = new HashSet<String>();
while (fieldIter.hasNext()) {
ModelField curField = fieldIter.next();
String fieldSet = curField.getFieldSet();
if (UtilValidate.isEmpty(fieldSet)) {
continue;
}
if (!fieldSetsToInclude.contains(fieldSet)) {
continue;
}
String fieldName = curField.getName();
if (addedFields.contains(fieldName)) {
continue;
}
reasonSets.add(fieldSet);
extraFields.add(fieldName);
addedFields.add(fieldName);
selectFields.add(curField);
}
if (verboseOn) {
Debug.logInfo("[" + modelEntity.getEntityName() + "]: auto-added select fields: " + extraFields, module);
Debug.logInfo("[" + modelEntity.getEntityName() + "]: auto-added field-sets: " + reasonSets, module);
}
}
} else {
selectFields = modelEntity.getFieldsUnmodifiable();
}
StringBuilder sqlBuffer = new StringBuilder("SELECT ");
if (findOptions.getDistinct()) {
sqlBuffer.append("DISTINCT ");
}
if (selectFields.size() > 0) {
modelEntity.colNameString(selectFields, sqlBuffer, "", ", ", "", datasource.getAliasViewColumns());
} else {
sqlBuffer.append("*");
}
// populate the info from entity-condition in the view-entity, if it is one and there is one
List<EntityCondition> viewWhereConditions = null;
List<EntityCondition> viewHavingConditions = null;
List<String> viewOrderByList = null;
if (modelViewEntity != null) {
viewWhereConditions = new LinkedList<EntityCondition>();
viewHavingConditions = new LinkedList<EntityCondition>();
viewOrderByList = new LinkedList<String>();
modelViewEntity.populateViewEntityConditionInformation(modelFieldTypeReader, viewWhereConditions, viewHavingConditions, viewOrderByList, null);
}
// FROM clause and when necessary the JOIN or LEFT JOIN clause(s) as well
sqlBuffer.append(SqlJdbcUtil.makeFromClause(modelEntity, modelFieldTypeReader, datasource));
// WHERE clause
List<EntityConditionParam> whereEntityConditionParams = new LinkedList<EntityConditionParam>();
makeConditionWhereString(sqlBuffer, " WHERE ", modelEntity, whereEntityCondition, viewWhereConditions, whereEntityConditionParams);
// GROUP BY clause for view-entity
if (modelViewEntity != null) {
modelViewEntity.colNameString(modelViewEntity.getGroupBysCopy(selectFields), sqlBuffer, " GROUP BY ", ", ", "", false);
}
// HAVING clause
List<EntityConditionParam> havingEntityConditionParams = new LinkedList<EntityConditionParam>();
makeConditionHavingString(sqlBuffer, " HAVING ", modelEntity, havingEntityCondition, viewHavingConditions, havingEntityConditionParams);
// ORDER BY clause
List<String> orderByExpanded = new LinkedList<String>();
// add the manually specified ones, then the ones in the view entity's entity-condition
if (orderBy != null) {
orderByExpanded.addAll(orderBy);
}
if (viewOrderByList != null) {
// add to end of other order by so that those in method call will override those in view
orderByExpanded.addAll(viewOrderByList);
}
sqlBuffer.append(SqlJdbcUtil.makeOrderByClause(modelEntity, orderByExpanded, datasource));
// OFFSET clause
makeOffsetString(sqlBuffer, findOptions);
// make the final SQL String
String sql = sqlBuffer.toString();
SQLProcessor sqlP = new SQLProcessor(delegator, helperInfo);
sqlP.prepareStatement(sql, findOptions.getSpecifyTypeAndConcur(), findOptions.getResultSetType(), findOptions.getResultSetConcurrency(), findOptions.getFetchSize(), findOptions.getMaxRows());
if (verboseOn) {
// put this inside an if statement so that we don't have to generate the string when not used...
if (Debug.verboseOn())
Debug.logVerbose("Setting the whereEntityConditionParams: " + whereEntityConditionParams, module);
}
// set all of the values from the Where EntityCondition
for (EntityConditionParam whereEntityConditionParam : whereEntityConditionParams) {
SqlJdbcUtil.setValue(sqlP, whereEntityConditionParam.getModelField(), modelEntity.getEntityName(), whereEntityConditionParam.getFieldValue(), modelFieldTypeReader);
}
if (verboseOn) {
// put this inside an if statement so that we don't have to generate the string when not used...
if (Debug.verboseOn())
Debug.logVerbose("Setting the havingEntityConditionParams: " + havingEntityConditionParams, module);
}
// set all of the values from the Having EntityCondition
for (EntityConditionParam havingEntityConditionParam : havingEntityConditionParams) {
SqlJdbcUtil.setValue(sqlP, havingEntityConditionParam.getModelField(), modelEntity.getEntityName(), havingEntityConditionParam.getFieldValue(), modelFieldTypeReader);
}
long queryStartTime = 0;
if (Debug.timingOn()) {
queryStartTime = System.currentTimeMillis();
}
sqlP.executeQuery();
if (Debug.timingOn()) {
long queryEndTime = System.currentTimeMillis();
long queryTotalTime = queryEndTime - queryStartTime;
if (queryTotalTime > 150) {
Debug.logTiming("Ran query in " + queryTotalTime + " milli-seconds: " + " EntityName: " + modelEntity.getEntityName() + " Sql: " + sql + " where clause:" + whereEntityConditionParams, module);
}
}
return new EntityListIterator(sqlP, modelEntity, selectFields, modelFieldTypeReader, this, whereEntityCondition, havingEntityCondition, findOptions.getDistinct());
}
Aggregations