Search in sources :

Example 11 with ModelKeyMap

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

the class DatabaseUtil method makeFkConstraintClause.

public String makeFkConstraintClause(ModelEntity entity, ModelRelation modelRelation, ModelEntity relModelEntity, int constraintNameClipLength, String fkStyle, boolean useFkInitiallyDeferred) {
    // make the two column lists
    StringBuilder mainCols = new StringBuilder();
    StringBuilder relCols = new StringBuilder();
    for (ModelKeyMap keyMap : modelRelation.getKeyMaps()) {
        ModelField mainField = entity.getField(keyMap.getFieldName());
        if (mainField == null) {
            Debug.logError("Bad key-map in entity [" + entity.getEntityName() + "] relation to [" + modelRelation.getTitle() + modelRelation.getRelEntityName() + "] for field [" + keyMap.getFieldName() + "]", module);
            return null;
        }
        if (mainCols.length() > 0) {
            mainCols.append(", ");
        }
        mainCols.append(mainField.getColName());
        ModelField relField = relModelEntity.getField(keyMap.getRelFieldName());
        if (relField == null) {
            Debug.logError("The field '" + keyMap.getRelFieldName() + "' was not found at related entity - check relations at entity '" + entity.getEntityName() + "'!", module);
        }
        if (relCols.length() > 0) {
            relCols.append(", ");
        }
        relCols.append(relField.getColName());
    }
    StringBuilder sqlBuf = new StringBuilder("");
    if ("name_constraint".equals(fkStyle)) {
        sqlBuf.append("CONSTRAINT ");
        String relConstraintName = makeFkConstraintName(modelRelation, constraintNameClipLength);
        sqlBuf.append(relConstraintName);
        sqlBuf.append(" FOREIGN KEY (");
        sqlBuf.append(mainCols.toString());
        sqlBuf.append(") REFERENCES ");
        sqlBuf.append(relModelEntity.getTableName(datasourceInfo));
        sqlBuf.append(" (");
        sqlBuf.append(relCols.toString());
        sqlBuf.append(")");
        if (useFkInitiallyDeferred) {
            sqlBuf.append(" INITIALLY DEFERRED");
        }
    } else if ("name_fk".equals(fkStyle)) {
        sqlBuf.append(" FOREIGN KEY ");
        String relConstraintName = makeFkConstraintName(modelRelation, constraintNameClipLength);
        sqlBuf.append(relConstraintName);
        sqlBuf.append(" (");
        sqlBuf.append(mainCols.toString());
        sqlBuf.append(") REFERENCES ");
        sqlBuf.append(relModelEntity.getTableName(datasourceInfo));
        sqlBuf.append(" (");
        sqlBuf.append(relCols.toString());
        sqlBuf.append(")");
        if (useFkInitiallyDeferred) {
            sqlBuf.append(" INITIALLY DEFERRED");
        }
    } else {
        String emsg = "ERROR: fk-style specified for this data-source is not valid: " + fkStyle;
        Debug.logError(emsg, module);
        throw new IllegalArgumentException(emsg);
    }
    return sqlBuf.toString();
}
Also used : ModelKeyMap(org.apache.ofbiz.entity.model.ModelKeyMap) ModelField(org.apache.ofbiz.entity.model.ModelField)

Example 12 with ModelKeyMap

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

the class GenericDelegator method getRelated.

/* (non-Javadoc)
     * @see org.apache.ofbiz.entity.Delegator#getRelated(java.lang.String, java.util.Map, java.util.List, org.apache.ofbiz.entity.GenericValue, boolean)
     */
@Override
public List<GenericValue> getRelated(String relationName, Map<String, ? extends Object> byAndFields, List<String> orderBy, GenericValue value, boolean useCache) throws GenericEntityException {
    ModelEntity modelEntity = value.getModelEntity();
    ModelRelation relation = modelEntity.getRelation(relationName);
    if (relation == null) {
        throw new GenericModelException("Could not find relation for relationName: " + relationName + " for value " + value);
    }
    // put the byAndFields (if not null) into the hash map first,
    // they will be overridden by value's fields if over-specified this is important for security and cleanliness
    Map<String, Object> fields = new HashMap<>();
    if (byAndFields != null) {
        fields.putAll(byAndFields);
    }
    for (ModelKeyMap keyMap : relation.getKeyMaps()) {
        fields.put(keyMap.getRelFieldName(), value.get(keyMap.getFieldName()));
    }
    return this.findByAnd(relation.getRelEntityName(), fields, orderBy, useCache);
}
Also used : ModelKeyMap(org.apache.ofbiz.entity.model.ModelKeyMap) HashMap(java.util.HashMap) ModelRelation(org.apache.ofbiz.entity.model.ModelRelation) UtilObject(org.apache.ofbiz.base.util.UtilObject) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity)

Example 13 with ModelKeyMap

use of org.apache.ofbiz.entity.model.ModelKeyMap 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 14 with ModelKeyMap

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

the class GenericEntity method checkFks.

/**
 * Checks to see if all foreign key records exist in the database. Will create a dummy value for
 * those missing when specified.
 *
 * @param insertDummy Create a dummy record using the provided fields
 * @return true if all FKs exist (or when all missing are created)
 * @throws GenericEntityException
 */
public boolean checkFks(boolean insertDummy) throws GenericEntityException {
    ModelEntity model = this.getModelEntity();
    Iterator<ModelRelation> relItr = model.getRelationsIterator();
    while (relItr.hasNext()) {
        ModelRelation relation = relItr.next();
        if ("one".equalsIgnoreCase(relation.getType())) {
            // see if the related value exists
            Map<String, Object> fields = new HashMap<>();
            for (ModelKeyMap keyMap : relation.getKeyMaps()) {
                fields.put(keyMap.getRelFieldName(), this.get(keyMap.getFieldName()));
            }
            EntityFieldMap ecl = EntityCondition.makeCondition(fields);
            long count = this.getDelegator().findCountByCondition(relation.getRelEntityName(), ecl, null, null);
            if (count == 0) {
                if (insertDummy) {
                    // create the new related value (dummy)
                    GenericValue newValue = this.getDelegator().makeValue(relation.getRelEntityName());
                    boolean allFieldsSet = true;
                    for (ModelKeyMap mkm : relation.getKeyMaps()) {
                        if (this.get(mkm.getFieldName()) != null) {
                            newValue.set(mkm.getRelFieldName(), this.get(mkm.getFieldName()));
                            if (Debug.infoOn()) {
                                Debug.logInfo("Set [" + mkm.getRelFieldName() + "] to - " + this.get(mkm.getFieldName()), module);
                            }
                        } else {
                            allFieldsSet = false;
                        }
                    }
                    if (allFieldsSet) {
                        if (Debug.infoOn()) {
                            Debug.logInfo("Creating place holder value : " + newValue, module);
                        }
                        // inherit create and update times from this value in order to make this not seem like new/fresh data
                        newValue.put(ModelEntity.CREATE_STAMP_FIELD, this.get(ModelEntity.CREATE_STAMP_FIELD));
                        newValue.put(ModelEntity.CREATE_STAMP_TX_FIELD, this.get(ModelEntity.CREATE_STAMP_TX_FIELD));
                        newValue.put(ModelEntity.STAMP_FIELD, this.get(ModelEntity.STAMP_FIELD));
                        newValue.put(ModelEntity.STAMP_TX_FIELD, this.get(ModelEntity.STAMP_TX_FIELD));
                        // set isFromEntitySync so that create/update stamp fields set above will be preserved
                        newValue.setIsFromEntitySync(true);
                        // check the FKs for the newly created entity
                        newValue.checkFks(true);
                        newValue.create();
                    }
                } else {
                    return false;
                }
            }
        }
    }
    return true;
}
Also used : ModelKeyMap(org.apache.ofbiz.entity.model.ModelKeyMap) HashMap(java.util.HashMap) ModelRelation(org.apache.ofbiz.entity.model.ModelRelation) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity) EntityFieldMap(org.apache.ofbiz.entity.condition.EntityFieldMap)

Aggregations

ModelKeyMap (org.apache.ofbiz.entity.model.ModelKeyMap)14 HashMap (java.util.HashMap)9 ModelEntity (org.apache.ofbiz.entity.model.ModelEntity)8 ModelField (org.apache.ofbiz.entity.model.ModelField)7 ModelRelation (org.apache.ofbiz.entity.model.ModelRelation)6 Delegator (org.apache.ofbiz.entity.Delegator)5 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)5 LinkedList (java.util.LinkedList)4 UtilObject (org.apache.ofbiz.base.util.UtilObject)4 GenericValue (org.apache.ofbiz.entity.GenericValue)4 Locale (java.util.Locale)3 Map (java.util.Map)3 GenericModelException (org.apache.ofbiz.entity.GenericModelException)3 EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)3 ModelViewEntity (org.apache.ofbiz.entity.model.ModelViewEntity)3 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)3 TreeSet (java.util.TreeSet)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 GeneralException (org.apache.ofbiz.base.util.GeneralException)2 DynamicViewEntity (org.apache.ofbiz.entity.model.DynamicViewEntity)2