Search in sources :

Example 41 with ModelField

use of org.apache.ofbiz.entity.model.ModelField 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());
}
Also used : GenericModelException(org.apache.ofbiz.entity.GenericModelException) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) LinkedList(java.util.LinkedList) SQLProcessor(org.apache.ofbiz.entity.jdbc.SQLProcessor) ModelField(org.apache.ofbiz.entity.model.ModelField) EntityFindOptions(org.apache.ofbiz.entity.util.EntityFindOptions) ModelViewEntity(org.apache.ofbiz.entity.model.ModelViewEntity) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) HashSet(java.util.HashSet) EntityConditionParam(org.apache.ofbiz.entity.condition.EntityConditionParam)

Example 42 with ModelField

use of org.apache.ofbiz.entity.model.ModelField in project ofbiz-framework by apache.

the class GenericDAO method update.

public int update(GenericEntity entity) throws GenericEntityException {
    ModelEntity modelEntity = entity.getModelEntity();
    // we don't want to update ALL fields, just the nonpk fields that are in the passed GenericEntity
    List<ModelField> partialFields = new LinkedList<ModelField>();
    Collection<String> keys = entity.getAllKeys();
    Iterator<ModelField> nopkIter = modelEntity.getNopksIterator();
    while (nopkIter.hasNext()) {
        ModelField curField = nopkIter.next();
        if (keys.contains(curField.getName())) {
            partialFields.add(curField);
        }
    }
    return customUpdate(entity, modelEntity, partialFields);
}
Also used : ModelField(org.apache.ofbiz.entity.model.ModelField) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity) LinkedList(java.util.LinkedList)

Example 43 with ModelField

use of org.apache.ofbiz.entity.model.ModelField in project ofbiz-framework by apache.

the class GenericDAO method selectByMultiRelation.

public List<GenericValue> selectByMultiRelation(GenericValue value, ModelRelation modelRelationOne, ModelEntity modelEntityOne, ModelRelation modelRelationTwo, ModelEntity modelEntityTwo, List<String> orderBy) throws GenericEntityException {
    // get the tables names
    String atable = modelEntityOne.getTableName(datasource);
    String ttable = modelEntityTwo.getTableName(datasource);
    // get the column name string to select
    StringBuilder selsb = new StringBuilder();
    List<String> fldlist = new LinkedList<String>();
    for (Iterator<ModelField> iterator = modelEntityTwo.getFieldsIterator(); iterator.hasNext(); ) {
        ModelField mf = iterator.next();
        fldlist.add(mf.getName());
        selsb.append(ttable).append(".").append(mf.getColName());
        if (iterator.hasNext()) {
            selsb.append(", ");
        } else {
            selsb.append(" ");
        }
    }
    // construct assoc->target relation string
    StringBuilder wheresb = new StringBuilder();
    for (ModelKeyMap mkm : modelRelationTwo.getKeyMaps()) {
        String lfname = mkm.getFieldName();
        String rfname = mkm.getRelFieldName();
        if (wheresb.length() > 0) {
            wheresb.append(" AND ");
        }
        wheresb.append(atable).append(".").append(modelEntityOne.getField(lfname).getColName()).append(" = ").append(ttable).append(".").append(modelEntityTwo.getField(rfname).getColName());
    }
    // construct the source entity qualifier
    // get the fields from relation description
    Map<ModelField, Object> bindMap = new HashMap<ModelField, Object>();
    for (ModelKeyMap mkm : modelRelationOne.getKeyMaps()) {
        // get the equivalent column names in the relation
        String sfldname = mkm.getFieldName();
        String lfldname = mkm.getRelFieldName();
        ModelField amf = modelEntityOne.getField(lfldname);
        String lcolname = amf.getColName();
        Object rvalue = value.get(sfldname);
        bindMap.put(amf, rvalue);
        // construct one condition
        if (wheresb.length() > 0) {
            wheresb.append(" AND ");
        }
        wheresb.append(atable).append(".").append(lcolname).append(" = ? ");
    }
    // construct a join sql query
    StringBuilder sqlsb = new StringBuilder();
    sqlsb.append("SELECT ");
    sqlsb.append(selsb.toString());
    sqlsb.append(" FROM ");
    sqlsb.append(atable).append(", ").append(ttable);
    sqlsb.append(" WHERE ");
    sqlsb.append(wheresb.toString());
    sqlsb.append(SqlJdbcUtil.makeOrderByClause(modelEntityTwo, orderBy, true, datasource));
    // now execute the query
    List<GenericValue> retlist = new LinkedList<GenericValue>();
    Delegator gd = value.getDelegator();
    try (SQLProcessor sqlP = new SQLProcessor(value.getDelegator(), helperInfo)) {
        sqlP.prepareStatement(sqlsb.toString());
        for (Map.Entry<ModelField, Object> entry : bindMap.entrySet()) {
            ModelField mf = entry.getKey();
            Object curvalue = entry.getValue();
            SqlJdbcUtil.setValue(sqlP, mf, modelEntityOne.getEntityName(), curvalue, modelFieldTypeReader);
        }
        sqlP.executeQuery();
        while (sqlP.next()) {
            Map<String, Object> emptyMap = Collections.emptyMap();
            GenericValue gv = gd.makeValue(modelEntityTwo.getEntityName(), emptyMap);
            // loop thru all columns for in one row
            int idx = 1;
            for (String fldname : fldlist) {
                ModelField mf = modelEntityTwo.getField(fldname);
                SqlJdbcUtil.getValue(sqlP.getResultSet(), idx, mf, gv, modelFieldTypeReader);
                idx++;
            }
            retlist.add(gv);
        }
    }
    return retlist;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) LinkedList(java.util.LinkedList) SQLProcessor(org.apache.ofbiz.entity.jdbc.SQLProcessor) ModelKeyMap(org.apache.ofbiz.entity.model.ModelKeyMap) ModelField(org.apache.ofbiz.entity.model.ModelField) Delegator(org.apache.ofbiz.entity.Delegator) HashMap(java.util.HashMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ModelKeyMap(org.apache.ofbiz.entity.model.ModelKeyMap)

Example 44 with ModelField

use of org.apache.ofbiz.entity.model.ModelField in project ofbiz-framework by apache.

the class GenericEntity method toString.

/**
 * Creates a String for the entity, overrides the default toString
 * This method is secure, it will not display encrypted fields
 *
 *@return String corresponding to this entity
 */
@Override
public String toString() {
    StringBuilder theString = new StringBuilder();
    theString.append("[GenericEntity:");
    theString.append(getEntityName());
    theString.append(']');
    for (String curKey : new TreeSet<>(fields.keySet())) {
        Object curValue = fields.get(curKey);
        ModelField field = this.getModelEntity().getField(curKey);
        if (field.getEncryptMethod().isEncrypted() && curValue instanceof String) {
            String encryptField = (String) curValue;
            // the encryptField may not actually be UTF8, it could be any
            // random encoding; just treat it as a series of raw bytes.
            // This won't give the same output as the value stored in the
            // database, but should be good enough for printing
            curValue = HashCrypt.cryptBytes(null, null, encryptField.getBytes(UtilIO.getUtf8()));
        }
        theString.append('[');
        theString.append(curKey);
        theString.append(',');
        theString.append(curValue);
        theString.append('(');
        theString.append(curValue != null ? curValue.getClass().getName() : "");
        theString.append(')');
        theString.append(']');
    }
    return theString.toString();
}
Also used : ModelField(org.apache.ofbiz.entity.model.ModelField) TreeSet(java.util.TreeSet)

Example 45 with ModelField

use of org.apache.ofbiz.entity.model.ModelField in project ofbiz-framework by apache.

the class GenericEntity method setAllFields.

/**
 * Intelligently sets fields on this entity from the Map of fields passed in
 * @param fields The fields Map to get the values from
 * @param setIfEmpty Used to specify whether empty/null values in the field Map should over-write non-empty values in this entity
 * @param namePrefix If not null or empty will be pre-pended to each field name (upper-casing the first letter of the field name first), and that will be used as the fields Map lookup name instead of the field-name
 * @param pks If null, get all values, if TRUE just get PKs, if FALSE just get non-PKs
 */
public void setAllFields(Map<? extends Object, ? extends Object> fields, boolean setIfEmpty, String namePrefix, Boolean pks) {
    if (fields == null) {
        return;
    }
    Iterator<ModelField> iter = null;
    if (pks != null) {
        if (pks.booleanValue()) {
            iter = this.getModelEntity().getPksIterator();
        } else {
            iter = this.getModelEntity().getNopksIterator();
        }
    } else {
        iter = this.getModelEntity().getFieldsIterator();
    }
    while (iter != null && iter.hasNext()) {
        ModelField curField = iter.next();
        String fieldName = curField.getName();
        String sourceFieldName = null;
        if (UtilValidate.isNotEmpty(namePrefix)) {
            sourceFieldName = namePrefix + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
        } else {
            sourceFieldName = curField.getName();
        }
        if (fields.containsKey(sourceFieldName)) {
            Object field = fields.get(sourceFieldName);
            if (setIfEmpty) {
                // if empty string, set to null
                if (field != null && field instanceof String && ((String) field).length() == 0) {
                    this.set(curField.getName(), null);
                } else {
                    this.set(curField.getName(), field);
                }
            } else {
                // okay, only set if not empty...
                if (field != null) {
                    // if it's a String then we need to check length, otherwise set it because it's not null
                    if (field instanceof String) {
                        String fieldStr = (String) field;
                        if (fieldStr.length() > 0) {
                            this.set(curField.getName(), fieldStr);
                        }
                    } else {
                        this.set(curField.getName(), field);
                    }
                }
            }
        }
    }
}
Also used : ModelField(org.apache.ofbiz.entity.model.ModelField)

Aggregations

ModelField (org.apache.ofbiz.entity.model.ModelField)55 ModelEntity (org.apache.ofbiz.entity.model.ModelEntity)28 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)16 LinkedList (java.util.LinkedList)14 ModelViewEntity (org.apache.ofbiz.entity.model.ModelViewEntity)13 HashMap (java.util.HashMap)10 GenericValue (org.apache.ofbiz.entity.GenericValue)10 ModelFieldType (org.apache.ofbiz.entity.model.ModelFieldType)10 ModelKeyMap (org.apache.ofbiz.entity.model.ModelKeyMap)10 Map (java.util.Map)8 SQLException (java.sql.SQLException)7 Locale (java.util.Locale)7 GenericModelException (org.apache.ofbiz.entity.GenericModelException)7 TreeSet (java.util.TreeSet)6 Delegator (org.apache.ofbiz.entity.Delegator)6 EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)6 GeneralException (org.apache.ofbiz.base.util.GeneralException)5 ModelParam (org.apache.ofbiz.service.ModelParam)5 SQLProcessor (org.apache.ofbiz.entity.jdbc.SQLProcessor)4 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)4