任何人都对如何实现一对多映射有很好的建议 SQLite
运用 ContentProvider
?如果你看看 Uri ContentProvider#insert(Uri, ContentValues)
你可以看到它有 ContentValues
包含要插入的数据的param。问题在于其目前的实施 ContentValues
不支持 put(String, Object)
方法和类是最终的,所以我无法扩展它。为什么这是一个问题?我的设计来了:
我有两个一对多关系的表。为了在代码中表示这些,我有2个模型对象。 1st表示主记录,并且具有一个第二个对象实例列表的字段。现在我在模型对象#1中有一个辅助方法返回 ContentValues
生成当前对象。填充原始字段是微不足道的 ContentValues#put
重载的方法,但我没有运气的清单。所以目前我的第二个表行只是一个字符串值,我生成一个逗号分隔的字符串然后我重新解析为String []里面 ContentProvider#insert
。感觉很难吃,所以也许有人可以暗示如何以更清洁的方式完成它。
这是一些代码。首先来自模型类:
public ContentValues toContentValues() {
ContentValues values = new ContentValues();
values.put(ITEM_ID, itemId);
values.put(NAME, name);
values.put(TYPES, concat(types));
return values;
}
private String concat(String[] values) { /* trivial */}
而这里是精简版 ContentProvider#insert
方法
public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.beginTransaction();
try {
// populate types
String[] types = ((String)values.get(Offer.TYPES)).split("|");
// we no longer need it
values.remove(Offer.TYPES);
// first insert row into OFFERS
final long rowId = db.insert("offers", Offer.NAME, values);
if (rowId > 0 && types != null) {
// now insert all types for the row
for (String t : types) {
ContentValues type = new ContentValues(8);
type.put(Offer.OFFER_ID, rowId);
type.put(Offer.TYPE, t);
// insert values into second table
db.insert("types", Offer.TYPE, type);
}
}
db.setTransactionSuccessful();
return ContentUris.withAppendedId(Offer.CONTENT_URI, rowId);
} catch (Exception e) {
Log.e(TAG, "Failed to insert record", e);
} finally {
db.endTransaction();
}
}