如前所述,精简版似乎不支持此功能。我写了一个简单的递归函数来保存所有引用的对象。我在让泛型发挥得很好时遇到了问题,所以最后我把它们全部删除了。我还为我的数据库对象创建了一个基本实体类。
所以这就是我写的。如果任何人都可以获得相同的代码来使用适当的泛型,或者可以对其进行改进,请随时编辑。
// Debugging identity tag
public static final String TAG = DatabaseHelper.class.getName();
// Static map of common DAO objects
@SuppressWarnings("rawtypes")
private static final Map<Class, Dao<?, Integer>> sDaoClassMap = new HashMap<Class, Dao<?,Integer>>();
/**
* Persist an entity to the underlying database.
*
* @param context
* @param entity
* @return boolean flag indicating success
*/
public static boolean create(Context context, Entity entity) {
// Get our database manager
DatabaseHelper databaseHelper = DatabaseHelper.getHelper(context);
try {
// Recursively save entity
create(databaseHelper, entity);
} catch (IllegalArgumentException e) {
Log.e(TAG, "Object is not an instance of the declaring class", e);
return false;
} catch (IllegalAccessException e) {
Log.e(TAG, "Field is not accessible from the current context", e);
return false;
} catch (SQLException e) {
Log.e(TAG, "Unable to create object", e);
return false;
}
// Release database helper
DatabaseHelper.release();
// Return true on success
return true;
}
/**
* Persist an entity to the underlying database.<br><br>
* For each field that has a DatabaseField annotation with foreign set to true,
* and is an instance of Entity, recursive attempt to persist that entity as well.
*
* @param databaseHelper
* @param entity
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws SQLException
*/
@SuppressWarnings("unchecked")
public static void create(DatabaseHelper databaseHelper, Entity entity) throws IllegalArgumentException, IllegalAccessException, SQLException {
// Class type of entity used for reflection
@SuppressWarnings("rawtypes")
Class clazz = entity.getClass();
// Search declared fields and save child entities before saving parent.
for(Field field : clazz.getDeclaredFields()) {
// Inspect annotations
for(Annotation annotation : field.getDeclaredAnnotations()) {
// Only consider fields with the DatabaseField annotation
if(annotation instanceof DatabaseField) {
// Check for foreign attribute
DatabaseField databaseField = (DatabaseField)annotation;
if(databaseField.foreign()) {
// Check for instance of Entity
Object object = field.get(entity);
if(object instanceof Entity) {
// Recursive persist referenced entity
create(databaseHelper, (Entity)object);
}
}
}
}
}
// Retrieve the common DAO for the entity class
Dao<Entity, Integer> dao = (Dao<Entity, Integer>) sDaoClassMap.get(clazz);
// If the DAO does not exist, create it and add it to the static map
if(dao == null) {
dao = BaseDaoImpl.createDao(databaseHelper.getConnectionSource(), clazz);
sDaoClassMap.put(clazz, dao);
}
// Persist the entity to the database
dao.create(entity);
}