com.j256.ormlite.field.DatabaseField Java Examples
The following examples show how to use
com.j256.ormlite.field.DatabaseField.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OrmLiteDao.java From AndroidBase with Apache License 2.0 | 6 votes |
/** * 过滤数据实体中DatabaseField注解的字段值为null的字段 * * @param t 过滤后不包含null字段的数据 * @param obj 被过滤的数据 */ private void setObjectValueIfNotNull(T t, Object obj) throws IllegalAccessException, NoSuchFieldException { Field[] fields = obj.getClass().getDeclaredFields(); Class<?> cls = t.getClass(); for (Field field : fields) { field.setAccessible(true); if (field.getAnnotation(DatabaseField.class) == null || "id".equals(field.getName())) { continue; } Object valueObj = field.get(obj); if (valueObj != null) { Field f = cls.getDeclaredField(field.getName()); if (f != null) { f.setAccessible(true); f.set(t, valueObj); } else { throw new IllegalAccessException("no this field:" + field.getName()); } } } }
Example #2
Source File: OrmLiteDao.java From AndroidBase with Apache License 2.0 | 6 votes |
/** * 获取对象DatabaseField注解的属性值不为空的属性名称和属性值 * * @param obj 数据实体对象 * @return 属性名称和属性值键值对集合 */ private Map<String, Object> getFieldsIfValueNotNull(Object obj) throws IllegalAccessException { Map<String, Object> map = new HashMap<>(); Field[] fields = obj.getClass().getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); if (field.getAnnotation(DatabaseField.class) == null) { continue; } Object valueObj = field.get(obj); if (valueObj != null) { map.put(field.getName(), valueObj); } } return map; }
Example #3
Source File: OrmliteReflection.java From poetry with Apache License 2.0 | 6 votes |
/** * Get SQLite column name for a given Field. * * @param field the model's field * @param databaseField the DatabaseField annotation for the specified Field * @return the SQLite column name */ public static String getFieldName(Field field, DatabaseField databaseField) { if (!databaseField.columnName().isEmpty()) { return databaseField.columnName(); } else if (OrmliteReflection.isForeign(databaseField)) { return field.getName() + sForeignIdFieldSuffix; } else { return field.getName(); } }
Example #4
Source File: OrmliteReflection.java From poetry with Apache License 2.0 | 6 votes |
/** * Find a Field with a DatabaseField annotation that defines it as foreign. * * @param annotationRetriever the annotation retriever that caches the annotations * @param parentClass the class to search for the Field * @param findClass the field class to search for * @return a Field or null */ public static @Nullable Field findForeignField(AnnotationRetriever annotationRetriever, Class<?> parentClass, Class<?> findClass) { for (Field field : parentClass.getDeclaredFields()) { DatabaseField database_field = annotationRetriever.getAnnotation(field, DatabaseField.class); if (database_field != null && isForeign(database_field) && findClass.isAssignableFrom(field.getType())) { return field; } } if (parentClass.getSuperclass() != null) { // Recursively check superclass return findForeignField(annotationRetriever, parentClass.getSuperclass(), findClass); } else { return null; } }
Example #5
Source File: DatabaseTableConfigUtil.java From ormlite-android with ISC License | 6 votes |
/** * Instead of calling the annotation methods directly, we peer inside the proxy and investigate the array of * AnnotationMember objects stored by the AnnotationFactory. */ private static DatabaseFieldConfig buildConfig(DatabaseField databaseField, String tableName, Field field) throws Exception { InvocationHandler proxy = Proxy.getInvocationHandler(databaseField); if (proxy.getClass() != annotationFactoryClazz) { return null; } // this should be an array of AnnotationMember objects Object elementsObject = elementsField.get(proxy); if (elementsObject == null) { return null; } DatabaseFieldConfig config = new DatabaseFieldConfig(field.getName()); Object[] objs = (Object[]) elementsObject; for (int i = 0; i < configFieldNums.length; i++) { Object value = valueField.get(objs[i]); if (value != null) { assignConfigField(configFieldNums[i], config, field, value); } } return config; }
Example #6
Source File: DatabaseTableConfig.java From ormlite-core with ISC License | 6 votes |
private static <T> FieldType[] extractFieldTypes(DatabaseType databaseType, Class<T> clazz, String tableName) throws SQLException { List<FieldType> fieldTypes = new ArrayList<FieldType>(); for (Class<?> classWalk = clazz; classWalk != null; classWalk = classWalk.getSuperclass()) { for (Field field : classWalk.getDeclaredFields()) { FieldType fieldType = FieldType.createFieldType(databaseType, tableName, field, clazz); if (fieldType != null) { fieldTypes.add(fieldType); } } } if (fieldTypes.isEmpty()) { throw new IllegalArgumentException( "No fields have a " + DatabaseField.class.getSimpleName() + " annotation in " + clazz); } return fieldTypes.toArray(new FieldType[fieldTypes.size()]); }
Example #7
Source File: OrmliteReflection.java From poetry with Apache License 2.0 | 5 votes |
/** * Get SQLite column name for a given Field. * * @param annotationRetriever the annotation retriever that caches the annotations * @param field the model's field * @return the SQLite column name */ public static String getFieldName(AnnotationRetriever annotationRetriever, Field field) { DatabaseField database_field = annotationRetriever.getAnnotation(field, DatabaseField.class); if (database_field == null) { throw new RuntimeException("DatabaseField annotation not found in " + field.getDeclaringClass().getName() + " for " + field.getName()); } return getFieldName(field, database_field); }
Example #8
Source File: OrmliteReflection.java From poetry with Apache License 2.0 | 5 votes |
/** * Find a Field with a DatabaseField annotation that defines it as being an id column. * * @param annotationRetriever the annotation retriever that caches the annotations * @param modelClass the class to find the ID field in * @return the Field or null */ public static @Nullable Field findIdField(AnnotationRetriever annotationRetriever, Class<?> modelClass) { for (Field field : modelClass.getDeclaredFields()) { DatabaseField database_field = annotationRetriever.getAnnotation(field, DatabaseField.class); if (database_field == null) { continue; } if (database_field.generatedId() || database_field.id()) { return field; } } if (modelClass.getSuperclass() != null) { // Recursively check superclass return findIdField(annotationRetriever, modelClass.getSuperclass()); } else { return null; } }
Example #9
Source File: DatabaseTableConfigUtil.java From ormlite-android with ISC License | 5 votes |
/** * Extract our configuration information from the field by looking for a {@link DatabaseField} annotation. */ private static DatabaseFieldConfig configFromField(DatabaseType databaseType, String tableName, Field field) throws SQLException { if (configFieldNums == null) { return DatabaseFieldConfig.fromField(databaseType, tableName, field); } /* * This, unfortunately, we can't get around. This creates a AnnotationFactory, an array of AnnotationMember * fields, and possibly another array of AnnotationMember values. This creates a lot of GC'd objects. */ DatabaseField databaseField = field.getAnnotation(DatabaseField.class); DatabaseFieldConfig config = null; try { if (databaseField != null) { config = buildConfig(databaseField, tableName, field); } } catch (Exception e) { // ignored so we will configure normally below } if (config == null) { /* * We configure this the old way because we might be using javax annotations, have a ForeignCollectionField, * or may still be using the deprecated annotations. At this point we know that there isn't a @DatabaseField * or we can't do our reflection hacks for some reason. */ return DatabaseFieldConfig.fromField(databaseType, tableName, field); } else { workedC++; return config; } }
Example #10
Source File: JsonPersister.java From poetry with Apache License 2.0 | 4 votes |
/** * Process an ID field giving JSON input and serialization information. * If no object is found in the database, a new one is inserted and its ID is returned. * * @param databaseField the Ormlite annotation * @param field the field that is annotated by databaseField * @param jsonObject the object that is being mapped * @param jsonKey the key where the value of the id field can be found within the jsonObject * @param tableName the table to insert a new row in case the ID is not found in the database * @return the ID field value of this object (never null) * @throws JSONException when the ID field value cannot be determined */ private Object processIdField(DatabaseField databaseField, Field field, JSONObject jsonObject, String jsonKey, String tableName) throws JSONException { String db_field_name = OrmliteReflection.getFieldName(field, databaseField); Object object_id = JsonUtils.getValue(jsonObject, jsonKey, field.getType()); if (object_id == null) { throw new RuntimeException(String.format("failed to get a value from JSON with key %s and type %s", jsonKey, field.getType().getName())); } String sql = String.format("SELECT * FROM '%s' WHERE %s = ? LIMIT 1", tableName, db_field_name); String[] selection_args = new String[] { object_id.toString() }; Cursor cursor = mDatabase.rawQuery(sql, selection_args); boolean object_exists = (cursor.getCount() > 0); cursor.close(); if (object_exists) { // return existing object id return object_id; } else // create object { ContentValues values = new ContentValues(1); if (!JsonUtils.copyValue(object_id, db_field_name, values)) { throw new JSONException(String.format("failed to process id field %s for table %s and jsonKey %s", field.getName(), tableName, jsonKey)); } long inserted_id = mDatabase.insert("'" + tableName + "'", null, values); if (inserted_id == -1) { throw new SQLiteException(String.format("failed to insert %s with id %s=%s", field.getType().getName(), db_field_name, object_id.toString())); } sLogger.info("prepared {} row (id={}/{})", tableName, object_id, inserted_id); return object_id; // don't return inserted_id, because it's always long (while the target type might be int or another type) } }
Example #11
Source File: JsonPersister.java From poetry with Apache License 2.0 | 4 votes |
private void processManyToMany(ManyToManyField manyToManyField, ForeignCollectionMapping foreignCollectionMapping, Object parentId, Class<?> parentClass) throws JSONException { if (foreignCollectionMapping.getJsonArray() == null) { // TODO: Delete mapping sLogger.warn("Mapping {} for type {} was null. Ignored it, but it should be deleted!", foreignCollectionMapping.getField().getName(), foreignCollectionMapping.getField().getType().getName()); return; } Field foreign_collection_field = foreignCollectionMapping.getField(); Class<?> target_class = OrmliteReflection.getForeignCollectionParameterType(foreign_collection_field); Field target_id_field = OrmliteReflection.findIdField(mAnnotationRetriever, target_class); if (target_id_field == null) { throw new RuntimeException("no id field found while processing foreign collection relation for " + target_class.getName()); } Field target_foreign_field = OrmliteReflection.findForeignField(mAnnotationRetriever, target_class, parentClass); if (target_foreign_field == null) { throw new RuntimeException("no foreign field found while processing foreign collection relation for " + target_class.getName()); } Field target_target_field = mFieldRetriever.getFirstFieldOfType(target_class, manyToManyField.targetType()); if (target_target_field == null) { throw new RuntimeException("ManyToMany problem: no ID field found for type " + manyToManyField.targetType().getName()); } List<Object> target_target_ids = persistArrayOfObjects(target_target_field.getType(), foreignCollectionMapping.getJsonArray()); // TODO: cache table name String target_table_name = OrmliteReflection.getTableName(mAnnotationRetriever, target_class); DatabaseField target_foreign_db_field = mAnnotationRetriever.getAnnotation(target_foreign_field, DatabaseField.class); String target_foreign_field_name = OrmliteReflection.getFieldName(target_foreign_field, target_foreign_db_field); String delete_select_clause = target_foreign_field_name + " = " + QueryUtils.parseAttribute(parentId); mDatabase.delete("'" + target_table_name + "'", delete_select_clause, new String[]{}); DatabaseField target_target_database_field = mAnnotationRetriever.getAnnotation(target_target_field, DatabaseField.class); String target_target_field_name = OrmliteReflection.getFieldName(target_target_field, target_target_database_field); // Insert new references for (int i = 0; i < target_target_ids.size(); ++i) { ContentValues values = new ContentValues(2); if (!JsonUtils.copyValue(parentId, target_foreign_field_name, values)) { throw new RuntimeException("parent id copy failed"); } if (!JsonUtils.copyValue(target_target_ids.get(i), target_target_field_name, values)) { throw new RuntimeException("target id copy failed"); } if (mDatabase.insert("'" + target_table_name + "'", null, values) == -1) { throw new RuntimeException("failed to insert item in " + target_table_name); } } }
Example #12
Source File: JsonPersister.java From poetry with Apache License 2.0 | 4 votes |
private void processManyToOne(ForeignCollectionMapping foreignCollectionMapping, Object parentId, Class<?> parentClass) throws JSONException { if (foreignCollectionMapping.getJsonArray() == null) { // TODO: Delete mapping sLogger.warn("Mapping {} for type {} was null. Ignored it, but it should be deleted!", foreignCollectionMapping.getField().getName(), foreignCollectionMapping.getField().getType().getName()); return; } Field foreign_collection_field = foreignCollectionMapping.getField(); Class<?> target_class = OrmliteReflection.getForeignCollectionParameterType(foreign_collection_field); Field target_id_field = OrmliteReflection.findIdField(mAnnotationRetriever, target_class); if (target_id_field == null) { throw new RuntimeException("no id field found while processing foreign collection relation for " + target_class.getName()); } Field target_foreign_field = OrmliteReflection.findForeignField(mAnnotationRetriever, target_class, parentClass); if (target_foreign_field == null) { throw new RuntimeException("no foreign field found while processing foreign collection relation for " + target_class.getName()); } ForeignCollectionFieldSingleTarget single_target_field = mAnnotationRetriever.getAnnotation(foreignCollectionMapping.getField(), ForeignCollectionFieldSingleTarget.class); List<Object> target_ids; if (single_target_field == null) { target_ids = persistArrayOfObjects(target_class, foreignCollectionMapping.getJsonArray()); } else { target_ids = persistArrayOfBaseTypes(target_class, foreignCollectionMapping.getJsonArray(), single_target_field); } DatabaseField target_foreign_field_db_annotation = mAnnotationRetriever.getAnnotation(target_foreign_field, DatabaseField.class); String target_foreign_field_name = OrmliteReflection.getFieldName(target_foreign_field, target_foreign_field_db_annotation); ContentValues values = new ContentValues(1); if (!JsonUtils.copyValue(parentId, target_foreign_field_name, values)) { throw new RuntimeException("failed to copy foreign key " + target_foreign_field_name + " in " + parentClass.getName() + ": key type " + parentId.getClass() + " is not supported"); } String[] target_id_args = new String[target_ids.size()]; String in_clause = QueryUtils.createInClause(target_ids, target_id_args); // update references to all target objects String target_table_name = OrmliteReflection.getTableName(mAnnotationRetriever, target_class); String target_id_field_name = OrmliteReflection.getFieldName(mAnnotationRetriever, target_id_field); String update_select_clause = target_id_field_name + " " + in_clause; mDatabase.update("'" + target_table_name + "'", values, update_select_clause, target_id_args); if (!Option.isEnabled(mOptions, Option.DISABLE_FOREIGN_COLLECTION_CLEANUP)) { // remove all objects that are not referenced to the parent anymore String delete_select_clause = target_id_field_name + " NOT " + in_clause + " AND " + target_foreign_field_name + " = " + QueryUtils.parseAttribute(parentId); mDatabase.delete("'" + target_table_name + "'", delete_select_clause, target_id_args); } }
Example #13
Source File: OrmliteReflection.java From poetry with Apache License 2.0 | 2 votes |
/** * Check if the provided DatabaseField is a foreign field. * * @param databaseField the annotation to check * @return true if foreign() is true, foreignAutoRefresh() is true or foreignColumnName() is set to a non-empty string */ public static boolean isForeign(DatabaseField databaseField) { return databaseField.foreign() || databaseField.foreignAutoRefresh() || !databaseField.foreignColumnName().isEmpty(); }
Example #14
Source File: OrmliteReflection.java From poetry with Apache License 2.0 | 2 votes |
/** * Check if the DatabaseField is an ID field. * * @param databaseField the annotation to check * @return true if id() or generatedId() are true */ public static boolean isId(DatabaseField databaseField) { return databaseField.id() || databaseField.generatedId(); }