Search in sources :

Example 1 with AssociationsInfo

use of org.litepal.crud.model.AssociationsInfo in project LitePal by LitePalFramework.

the class LitePalBase method addIntoAssociationInfoCollection.

/**
	 * Package a {@link org.litepal.crud.model.AssociationsInfo}, and add it into
	 * {@link #mAssociationInfos} Collection.
	 * 
	 * @param selfClassName
	 *            The class name of self model.
	 * @param associatedClassName
	 *            The class name of the class which associated with self class.
	 * @param classHoldsForeignKey
	 *            The class which holds foreign key.
	 * @param associateOtherModelFromSelf
	 *            The field of self class to declare has association with other
	 *            class.
	 * @param associateSelfFromOtherModel
	 *            The field of the associated class to declare has association
	 *            with self class.
	 * @param associationType
	 *            The association type.
	 */
private void addIntoAssociationInfoCollection(String selfClassName, String associatedClassName, String classHoldsForeignKey, Field associateOtherModelFromSelf, Field associateSelfFromOtherModel, int associationType) {
    AssociationsInfo associationInfo = new AssociationsInfo();
    associationInfo.setSelfClassName(selfClassName);
    associationInfo.setAssociatedClassName(associatedClassName);
    associationInfo.setClassHoldsForeignKey(classHoldsForeignKey);
    associationInfo.setAssociateOtherModelFromSelf(associateOtherModelFromSelf);
    associationInfo.setAssociateSelfFromOtherModel(associateSelfFromOtherModel);
    associationInfo.setAssociationType(associationType);
    mAssociationInfos.add(associationInfo);
}
Also used : AssociationsInfo(org.litepal.crud.model.AssociationsInfo)

Example 2 with AssociationsInfo

use of org.litepal.crud.model.AssociationsInfo in project LitePal by LitePalFramework.

the class DataHandler method setValueToModel.

/**
	 * Get value from database by cursor, then set the value into modelInstance.
	 * 
	 * @param modelInstance
	 *            The model to set into.
	 * @param supportedFields
	 *            Corresponding to each column in database.
	 * @param foreignKeyAssociations
	 *            Associated classes which have foreign keys in the current
	 *            model's table.
	 * @param cursor
	 *            Use to get value from database.
     * @param sparseArray
     *            Use SparseArray to cache the query information at first loop. Then the rest loop
     *            can get query information directly to speed up.
	 * @throws SecurityException
	 * @throws IllegalArgumentException
	 * @throws NoSuchMethodException
	 * @throws IllegalAccessException
	 * @throws java.lang.reflect.InvocationTargetException
	 */
protected void setValueToModel(Object modelInstance, List<Field> supportedFields, List<AssociationsInfo> foreignKeyAssociations, Cursor cursor, SparseArray<QueryInfoCache> sparseArray) throws SecurityException, IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    int cacheSize = sparseArray.size();
    if (cacheSize > 0) {
        for (int i = 0; i < cacheSize; i++) {
            int columnIndex = sparseArray.keyAt(i);
            QueryInfoCache cache = sparseArray.get(columnIndex);
            setToModelByReflection(modelInstance, cache.field, columnIndex, cache.getMethodName, cursor);
        }
    } else {
        for (Field field : supportedFields) {
            String getMethodName = genGetColumnMethod(field);
            String columnName = isIdColumn(field.getName()) ? "id" : DBUtility.convertToValidColumnName(field.getName());
            int columnIndex = cursor.getColumnIndex(BaseUtility.changeCase(columnName));
            if (columnIndex != -1) {
                setToModelByReflection(modelInstance, field, columnIndex, getMethodName, cursor);
                QueryInfoCache cache = new QueryInfoCache();
                cache.getMethodName = getMethodName;
                cache.field = field;
                sparseArray.put(columnIndex, cache);
            }
        }
    }
    if (foreignKeyAssociations != null) {
        for (AssociationsInfo associationInfo : foreignKeyAssociations) {
            String foreignKeyColumn = getForeignKeyColumnName(DBUtility.getTableNameByClassName(associationInfo.getAssociatedClassName()));
            int columnIndex = cursor.getColumnIndex(foreignKeyColumn);
            if (columnIndex != -1) {
                long associatedClassId = cursor.getLong(columnIndex);
                try {
                    DataSupport associatedObj = (DataSupport) DataSupport.find(Class.forName(associationInfo.getAssociatedClassName()), associatedClassId);
                    if (associatedObj != null) {
                        setFieldValue((DataSupport) modelInstance, associationInfo.getAssociateOtherModelFromSelf(), associatedObj);
                    }
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
Also used : Field(java.lang.reflect.Field) AssociationsInfo(org.litepal.crud.model.AssociationsInfo)

Example 3 with AssociationsInfo

use of org.litepal.crud.model.AssociationsInfo in project LitePal by LitePalFramework.

the class DeleteHandler method analyzeAssociations.

/**
	 * Analyze the associations of baseObj and store the result in it. The
	 * associations will be used when deleting referenced data of baseObj.
	 * 
	 * @param baseObj
	 *            The record to delete.
	 */
private Collection<AssociationsInfo> analyzeAssociations(DataSupport baseObj) {
    try {
        Collection<AssociationsInfo> associationInfos = getAssociationInfo(baseObj.getClassName());
        analyzeAssociatedModels(baseObj, associationInfos);
        return associationInfos;
    } catch (Exception e) {
        throw new DataSupportException(e.getMessage(), e);
    }
}
Also used : DataSupportException(org.litepal.exceptions.DataSupportException) AssociationsInfo(org.litepal.crud.model.AssociationsInfo) DataSupportException(org.litepal.exceptions.DataSupportException)

Example 4 with AssociationsInfo

use of org.litepal.crud.model.AssociationsInfo in project LitePal by LitePalFramework.

the class DataHandler method setAssociatedModel.

/**
	 * Finds the associated models of baseObj, then set them into baseObj.
	 * 
	 * @param baseObj
	 *            The class of base object.
	 */
@SuppressWarnings({ "rawtypes", "unchecked" })
private void setAssociatedModel(DataSupport baseObj) {
    if (fkInOtherModel == null) {
        return;
    }
    for (AssociationsInfo info : fkInOtherModel) {
        Cursor cursor = null;
        String associatedClassName = info.getAssociatedClassName();
        boolean isM2M = info.getAssociationType() == Const.Model.MANY_TO_MANY;
        try {
            List<Field> supportedFields = getSupportedFields(associatedClassName);
            List<Field> supportedGenericFields = getSupportedGenericFields(associatedClassName);
            if (isM2M) {
                String tableName = baseObj.getTableName();
                String associatedTableName = DBUtility.getTableNameByClassName(associatedClassName);
                String intermediateTableName = DBUtility.getIntermediateTableName(tableName, associatedTableName);
                StringBuilder sql = new StringBuilder();
                sql.append("select * from ").append(associatedTableName).append(" a inner join ").append(intermediateTableName).append(" b on a.id = b.").append(associatedTableName + "_id").append(" where b.").append(tableName).append("_id = ?");
                cursor = DataSupport.findBySQL(BaseUtility.changeCase(sql.toString()), String.valueOf(baseObj.getBaseObjId()));
            } else {
                String foreignKeyColumn = getForeignKeyColumnName(DBUtility.getTableNameByClassName(info.getSelfClassName()));
                String associatedTableName = DBUtility.getTableNameByClassName(associatedClassName);
                cursor = mDatabase.query(BaseUtility.changeCase(associatedTableName), null, foreignKeyColumn + "=?", new String[] { String.valueOf(baseObj.getBaseObjId()) }, null, null, null, null);
            }
            if (cursor != null && cursor.moveToFirst()) {
                SparseArray<QueryInfoCache> queryInfoCacheSparseArray = new SparseArray<QueryInfoCache>();
                Map<Field, GenericModel> genericModelMap = new HashMap<Field, GenericModel>();
                do {
                    DataSupport modelInstance = (DataSupport) createInstanceFromClass(Class.forName(associatedClassName));
                    giveBaseObjIdValue(modelInstance, cursor.getLong(cursor.getColumnIndexOrThrow("id")));
                    setValueToModel(modelInstance, supportedFields, null, cursor, queryInfoCacheSparseArray);
                    setGenericValueToModel(modelInstance, supportedGenericFields, genericModelMap);
                    if (info.getAssociationType() == Const.Model.MANY_TO_ONE || isM2M) {
                        Field field = info.getAssociateOtherModelFromSelf();
                        Collection collection = (Collection) getFieldValue(baseObj, field);
                        if (collection == null) {
                            if (isList(field.getType())) {
                                collection = new ArrayList();
                            } else {
                                collection = new HashSet();
                            }
                            DynamicExecutor.setField(baseObj, field.getName(), collection, baseObj.getClass());
                        }
                        collection.add(modelInstance);
                    } else if (info.getAssociationType() == Const.Model.ONE_TO_ONE) {
                        setFieldValue(baseObj, info.getAssociateOtherModelFromSelf(), modelInstance);
                    }
                } while (cursor.moveToNext());
                queryInfoCacheSparseArray.clear();
                genericModelMap.clear();
            }
        } catch (Exception e) {
            throw new DataSupportException(e.getMessage(), e);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Cursor(android.database.Cursor) DatabaseGenerateException(org.litepal.exceptions.DatabaseGenerateException) DataSupportException(org.litepal.exceptions.DataSupportException) InvocationTargetException(java.lang.reflect.InvocationTargetException) GenericModel(org.litepal.tablemanager.model.GenericModel) Field(java.lang.reflect.Field) SparseArray(android.util.SparseArray) DataSupportException(org.litepal.exceptions.DataSupportException) Collection(java.util.Collection) AssociationsInfo(org.litepal.crud.model.AssociationsInfo) HashSet(java.util.HashSet)

Example 5 with AssociationsInfo

use of org.litepal.crud.model.AssociationsInfo in project LitePal by LitePalFramework.

the class UpdateHandler method analyzeAssociations.

/**
	 * Analyze the associations of baseObj and store the result in it. The
	 * associations will be used when deleting referenced data of baseObj.
	 * Unused currently.
	 * 
	 * @param baseObj
	 *            The record to update.
	 */
private void analyzeAssociations(DataSupport baseObj) {
    try {
        Collection<AssociationsInfo> associationInfos = getAssociationInfo(baseObj.getClassName());
        analyzeAssociatedModels(baseObj, associationInfos);
    } catch (Exception e) {
        throw new DataSupportException(e.getMessage(), e);
    }
}
Also used : DataSupportException(org.litepal.exceptions.DataSupportException) AssociationsInfo(org.litepal.crud.model.AssociationsInfo) DataSupportException(org.litepal.exceptions.DataSupportException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Aggregations

AssociationsInfo (org.litepal.crud.model.AssociationsInfo)6 DataSupportException (org.litepal.exceptions.DataSupportException)3 Field (java.lang.reflect.Field)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 Cursor (android.database.Cursor)1 SparseArray (android.util.SparseArray)1 ArrayList (java.util.ArrayList)1 Collection (java.util.Collection)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 DatabaseGenerateException (org.litepal.exceptions.DatabaseGenerateException)1 GenericModel (org.litepal.tablemanager.model.GenericModel)1