Search in sources :

Example 31 with ModelViewEntity

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

the class DatabaseUtil method deleteTable.

public void deleteTable(ModelEntity entity, List<String> messages) {
    if (entity == null) {
        String errMsg = "ModelEntity was null and is required to delete a table";
        Debug.logError(errMsg, module);
        if (messages != null)
            messages.add(errMsg);
        return;
    }
    if (entity instanceof ModelViewEntity) {
        // if (messages != null) messages.add(errMsg);
        return;
    }
    String message = "Deleting table for entity [" + entity.getEntityName() + "]";
    Debug.logImportant(message, module);
    if (messages != null)
        messages.add(message);
    StringBuilder sqlBuf = new StringBuilder("DROP TABLE ");
    sqlBuf.append(entity.getTableName(datasourceInfo));
    if (Debug.verboseOn())
        Debug.logVerbose("[deleteTable] sql=" + sqlBuf.toString(), module);
    try (Connection connection = getConnectionLogged(messages);
        Statement stmt = connection.createStatement()) {
        stmt.executeUpdate(sqlBuf.toString());
    } catch (SQLException e) {
        String errMsg = "SQL Exception while executing the following:\n" + sqlBuf.toString() + "\nError was: " + e.toString();
        Debug.logError(errMsg, module);
        if (messages != null)
            messages.add(errMsg);
    }
}
Also used : SQLException(java.sql.SQLException) Statement(java.sql.Statement) ModelViewEntity(org.apache.ofbiz.entity.model.ModelViewEntity) Connection(java.sql.Connection)

Example 32 with ModelViewEntity

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

the class GenericDAO method singleInsert.

private int singleInsert(GenericEntity entity, ModelEntity modelEntity, List<ModelField> fieldsToSave, SQLProcessor sqlP) throws GenericEntityException {
    if (modelEntity instanceof ModelViewEntity) {
        return singleUpdateView(entity, (ModelViewEntity) modelEntity, fieldsToSave, sqlP);
    }
    // if we have a STAMP_TX_FIELD or CREATE_STAMP_TX_FIELD then set it with NOW, always do this before the STAMP_FIELD
    // NOTE: these fairly complicated if statements have a few objectives:
    // 1. don't run the TransationUtil.getTransaction*Stamp() methods when we don't need to
    // 2. don't set the stamp values if it is from an EntitySync (ie maintain original values), unless the stamps are null then set it anyway, ie even if it was from an EntitySync (also used for imports and such)
    boolean stampTxIsField = modelEntity.isField(ModelEntity.STAMP_TX_FIELD);
    boolean createStampTxIsField = modelEntity.isField(ModelEntity.CREATE_STAMP_TX_FIELD);
    if ((stampTxIsField || createStampTxIsField) && (!entity.getIsFromEntitySync() || (stampTxIsField && entity.get(ModelEntity.STAMP_TX_FIELD) == null) || (createStampTxIsField && entity.get(ModelEntity.CREATE_STAMP_TX_FIELD) == null))) {
        Timestamp txStartStamp = TransactionUtil.getTransactionStartStamp();
        if (stampTxIsField && (!entity.getIsFromEntitySync() || entity.get(ModelEntity.STAMP_TX_FIELD) == null)) {
            entity.set(ModelEntity.STAMP_TX_FIELD, txStartStamp);
            addFieldIfMissing(fieldsToSave, ModelEntity.STAMP_TX_FIELD, modelEntity);
        }
        if (createStampTxIsField && (!entity.getIsFromEntitySync() || entity.get(ModelEntity.CREATE_STAMP_TX_FIELD) == null)) {
            entity.set(ModelEntity.CREATE_STAMP_TX_FIELD, txStartStamp);
            addFieldIfMissing(fieldsToSave, ModelEntity.CREATE_STAMP_TX_FIELD, modelEntity);
        }
    }
    // if we have a STAMP_FIELD or CREATE_STAMP_FIELD then set it with NOW
    boolean stampIsField = modelEntity.isField(ModelEntity.STAMP_FIELD);
    boolean createStampIsField = modelEntity.isField(ModelEntity.CREATE_STAMP_FIELD);
    if ((stampIsField || createStampIsField) && (!entity.getIsFromEntitySync() || (stampIsField && entity.get(ModelEntity.STAMP_FIELD) == null) || (createStampIsField && entity.get(ModelEntity.CREATE_STAMP_FIELD) == null))) {
        Timestamp startStamp = TransactionUtil.getTransactionUniqueNowStamp();
        if (stampIsField && (!entity.getIsFromEntitySync() || entity.get(ModelEntity.STAMP_FIELD) == null)) {
            entity.set(ModelEntity.STAMP_FIELD, startStamp);
            addFieldIfMissing(fieldsToSave, ModelEntity.STAMP_FIELD, modelEntity);
        }
        if (createStampIsField && (!entity.getIsFromEntitySync() || entity.get(ModelEntity.CREATE_STAMP_FIELD) == null)) {
            entity.set(ModelEntity.CREATE_STAMP_FIELD, startStamp);
            addFieldIfMissing(fieldsToSave, ModelEntity.CREATE_STAMP_FIELD, modelEntity);
        }
    }
    StringBuilder sqlB = new StringBuilder("INSERT INTO ").append(modelEntity.getTableName(datasource)).append(" (");
    modelEntity.colNameString(fieldsToSave, sqlB, "");
    sqlB.append(") VALUES (");
    modelEntity.fieldsStringList(fieldsToSave, sqlB, "?", ", ");
    String sql = sqlB.append(")").toString();
    try {
        sqlP.prepareStatement(sql);
        SqlJdbcUtil.setValues(sqlP, fieldsToSave, entity, modelFieldTypeReader);
        int retVal = sqlP.executeUpdate();
        entity.synchronizedWithDatasource();
        return retVal;
    } catch (GenericEntityException e) {
        throw new GenericEntityException("Error while inserting: " + entity.toString(), e);
    }
}
Also used : GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) ModelViewEntity(org.apache.ofbiz.entity.model.ModelViewEntity) Timestamp(java.sql.Timestamp)

Example 33 with ModelViewEntity

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

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

the class GenericDAO method singleUpdate.

private int singleUpdate(GenericEntity entity, ModelEntity modelEntity, List<ModelField> fieldsToSave, SQLProcessor sqlP) throws GenericEntityException {
    if (modelEntity instanceof ModelViewEntity) {
        return singleUpdateView(entity, (ModelViewEntity) modelEntity, fieldsToSave, sqlP);
    }
    // no non-primaryKey fields, update doesn't make sense, so don't do it
    if (fieldsToSave.size() <= 0) {
        if (Debug.verboseOn())
            Debug.logVerbose("Trying to do an update on an entity with no non-PK fields, returning having done nothing; entity=" + entity, module);
        // returning one because it was effectively updated, ie the same thing, so don't trigger any errors elsewhere
        return 1;
    }
    if (modelEntity.lock()) {
        GenericEntity entityCopy = GenericEntity.createGenericEntity(entity);
        select(entityCopy, sqlP);
        Object stampField = entity.get(ModelEntity.STAMP_FIELD);
        if ((stampField != null) && (!stampField.equals(entityCopy.get(ModelEntity.STAMP_FIELD)))) {
            String lockedTime = entityCopy.getTimestamp(ModelEntity.STAMP_FIELD).toString();
            throw new EntityLockedException("You tried to update an old version of this data. Version locked: (" + lockedTime + ")");
        }
    }
    // 2. don't set the stamp values if it is from an EntitySync (ie maintain original values), unless the stamps are null then set it anyway, ie even if it was from an EntitySync (also used for imports and such)
    if (modelEntity.isField(ModelEntity.STAMP_TX_FIELD) && (!entity.getIsFromEntitySync() || entity.get(ModelEntity.STAMP_TX_FIELD) == null)) {
        entity.set(ModelEntity.STAMP_TX_FIELD, TransactionUtil.getTransactionStartStamp());
        addFieldIfMissing(fieldsToSave, ModelEntity.STAMP_TX_FIELD, modelEntity);
    }
    // if we have a STAMP_FIELD then update it with NOW.
    if (modelEntity.isField(ModelEntity.STAMP_FIELD) && (!entity.getIsFromEntitySync() || entity.get(ModelEntity.STAMP_FIELD) == null)) {
        entity.set(ModelEntity.STAMP_FIELD, TransactionUtil.getTransactionUniqueNowStamp());
        addFieldIfMissing(fieldsToSave, ModelEntity.STAMP_FIELD, modelEntity);
    }
    StringBuilder sql = new StringBuilder().append("UPDATE ").append(modelEntity.getTableName(datasource)).append(" SET ");
    modelEntity.colNameString(fieldsToSave, sql, "", "=?, ", "=?", false);
    sql.append(" WHERE ");
    SqlJdbcUtil.makeWhereStringFromFields(sql, modelEntity.getPkFieldsUnmodifiable(), entity, "AND");
    int retVal = 0;
    try {
        sqlP.prepareStatement(sql.toString());
        SqlJdbcUtil.setValues(sqlP, fieldsToSave, entity, modelFieldTypeReader);
        SqlJdbcUtil.setPkValues(sqlP, modelEntity, entity, modelFieldTypeReader);
        retVal = sqlP.executeUpdate();
        entity.synchronizedWithDatasource();
    } catch (GenericEntityException e) {
        throw new GenericEntityException("Error while updating: " + entity.toString(), e);
    }
    if (retVal == 0) {
        throw new GenericEntityNotFoundException("Tried to update an entity that does not exist, entity: " + entity.toString());
    }
    return retVal;
}
Also used : GenericEntity(org.apache.ofbiz.entity.GenericEntity) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) ModelViewEntity(org.apache.ofbiz.entity.model.ModelViewEntity) GenericEntityNotFoundException(org.apache.ofbiz.entity.GenericEntityNotFoundException) EntityLockedException(org.apache.ofbiz.entity.EntityLockedException)

Example 35 with ModelViewEntity

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

the class GenericEntity method get.

/**
 * Same as the getResource method that does not take resource name, but instead allows manually
 *    specifying the resource name. In general you should use the other method for more consistent
 *    naming and use of the corresponding properties files.
 * @param name The name of the field on the entity
 * @param resource The name of the resource to get the value from; if null defaults to the
 *    default-resource-name on the entity definition, if specified there
 * @param locale The locale to use when finding the ResourceBundle, if null uses the default
 *    locale for the current instance of Java
 * @return If the specified resource is found and contains a key as described above, then that
 *    property value is returned; otherwise returns the field value
 */
public Object get(String name, String resource, Locale locale) {
    Object fieldValue = get(name);
    // In case of view entity first try to retrieve with View field names
    ModelEntity modelEntityToUse = this.getModelEntity();
    Object resourceValue = get(this.getModelEntity(), modelEntityToUse, name, resource, locale);
    if (resourceValue == null) {
        if (modelEntityToUse instanceof ModelViewEntity) {
            // now try to retrieve with the field heading from the real entity linked to the view
            ModelViewEntity modelViewEntity = (ModelViewEntity) modelEntityToUse;
            Iterator<ModelAlias> it = modelViewEntity.getAliasesIterator();
            while (it.hasNext()) {
                ModelAlias modelAlias = it.next();
                if (modelAlias.getName().equalsIgnoreCase(name)) {
                    modelEntityToUse = modelViewEntity.getMemberModelEntity(modelAlias.getEntityAlias());
                    name = modelAlias.getField();
                    break;
                }
            }
            resourceValue = get(this.getModelEntity(), modelEntityToUse, name, resource, locale);
            if (resourceValue == null) {
                return fieldValue;
            }
            return resourceValue;
        }
        return fieldValue;
    }
    return resourceValue;
}
Also used : ModelViewEntity(org.apache.ofbiz.entity.model.ModelViewEntity) ModelAlias(org.apache.ofbiz.entity.model.ModelViewEntity.ModelAlias) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity)

Aggregations

ModelViewEntity (org.apache.ofbiz.entity.model.ModelViewEntity)37 ModelEntity (org.apache.ofbiz.entity.model.ModelEntity)16 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)14 LinkedList (java.util.LinkedList)13 ModelField (org.apache.ofbiz.entity.model.ModelField)13 SQLException (java.sql.SQLException)11 Connection (java.sql.Connection)7 Statement (java.sql.Statement)7 EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)7 GenericModelException (org.apache.ofbiz.entity.GenericModelException)6 ModelFieldType (org.apache.ofbiz.entity.model.ModelFieldType)6 ModelKeyMap (org.apache.ofbiz.entity.model.ModelKeyMap)6 ModelRelation (org.apache.ofbiz.entity.model.ModelRelation)6 GenericNotImplementedException (org.apache.ofbiz.entity.GenericNotImplementedException)5 HashMap (java.util.HashMap)4 TreeSet (java.util.TreeSet)4 GenericValue (org.apache.ofbiz.entity.GenericValue)4 IOException (java.io.IOException)3 Map (java.util.Map)3 GenericDataSourceException (org.apache.ofbiz.entity.GenericDataSourceException)3