我需要插入相关的订单
及其相应的详细信息
数据。
I need to insert data related to an Order
and its corresponding Detail
.
如果没有一个的ContentProvider
我会做这样的事情:
Without a ContentProvider
I would do something like this:
public boolean insertOrder(Order order, ArrayList<OrderDetail> items) {
boolean wasSuccessful = false;
ContentValues cvOrder = new ContentValues();
cvPedido.put(ORDER_CUSTOMER_ID, order.getCustomerId());
cvPedido.put(ORDER_CUSTOMER_NAME, order.getCustomerName());
String insertQuery = "INSERT INTO " + ORDER_DETAIL_TABLE
+ " VALUES (?,?)";
//...
try {
this.openWriteableDB();
SQLiteStatement statement = db.compileStatement(insertQuery);
db.beginTransaction();
long idOrder = db.insertOrThrow(ORDER_TABLE, null, cvOrder);
if (idOrder > 0) {
for (int i = 0; i < items.size(); i++) {
OrderDetail detail=items.get(i);
statement.clearBindings();
statement.bindString(1, detail.getDescription);
statement.bindDouble(2, detail.getPrice);
//...
statement.execute();
}
db.setTransactionSuccessful();
wasSuccessful = true;
}
} finally {
db.endTransaction();
this.closeDB();
}
return wasSuccessful;
}
现在的问题是,现在我想用一个的ContentProvider
,我不知道该怎么做这样的病例,其中约两个或多个表中的数据必须是传递给一个CRUD操作,知道插入
操作只接受两个参数:
The problem is that now I want to use a ContentProvider
and I don't know what to do with this kind of cases where data about two or more tables must be passed to a single CRUD operation, knowing that a insert
operation only accepts two parameters :
@Override
public Uri insert(Uri uri, ContentValues values) {
}
您在ContentProvider的做的时候,你必须在一个事务中插入关系数据是什么?
What do you do in a ContentProvider when you have to insert relational data in a transaction?
在此先感谢。
您应该使用的 ContentProviderOperation 。因为这是你的的ContentProvider
则可以保证 applyBatch()
将事务中执行的所有操作。所有标准的内容提供商也保证了这样的话。
You should use ContentProviderOperation. Since it's your ContentProvider
you can assure that applyBatch()
will execute all operations within a transaction. All standard content providers also ensure that that's the case.
请参阅有关ContentProviderOperation 一般我的博客职位和我对其他职位如何使用withBackReference()来访问previous操作结果 - 您需要访问的orderId
。
See my blog post about ContentProviderOperation in general and my other post about how to use withBackReference() to access results of previous operations - which you need to access the orderId
.
一个重要警告:所有的 ContentProviderOperations
一个批次都必须使用同一个部门 - 但可以使用不同的URI!你的情况应该是没有问题的。
One important caveat: All ContentProviderOperations
of one batch must use the same authority - but can use different URIs! In your case that should be no problem.
上一篇:完成非零退出值3