Java 如何使带有反向引用的批插入生效?
以下是我已经花了数小时研究的Android问题: 我在表车中插入对象,然后在表驱动程序中插入对象。我需要正确设置驾驶员的外键,以引用刚刚插入的车行。此外,如果无法保存在行驾驶员,也不应保存车辆。事务组语义 我正在使用ContentProvider方法 我知道我应该使用批插入和withValueBackReference来完成此任务 示例代码:Java 如何使带有反向引用的批插入生效?,java,android,sqlite,android-sqlite,sqliteopenhelper,Java,Android,Sqlite,Android Sqlite,Sqliteopenhelper,以下是我已经花了数小时研究的Android问题: 我在表车中插入对象,然后在表驱动程序中插入对象。我需要正确设置驾驶员的外键,以引用刚刚插入的车行。此外,如果无法保存在行驾驶员,也不应保存车辆。事务组语义 我正在使用ContentProvider方法 我知道我应该使用批插入和withValueBackReference来完成此任务 示例代码: // (populate carData obejct..) ArrayList<ContentProviderOperation> opL
// (populate carData obejct..)
ArrayList<ContentProviderOperation> opList = new
ArrayList<ContentProviderOperation>();
ContentValues carv = new ContentValues();
carv.put(Car.CAR_MAKE, carData.make);
carv.put(Car.CAR_MODEL, carData.model);
carv.put(BaseColumns._ID, 0); // this HAS to be here or withBackValues doesn't work
opList.add(ContentProviderOperation.newInsert(Car.CONTENT_URI).withValues(carv).build());
ContentValues driverv = new ContentValues();
driverv.put(Driver.DRIVER_NAME, carData.driverName);
driverv.put(Driver.DRIVER_CAR_FK, 0); // THIS should set the ID of the car above!
opList.add(ContentProviderOperation. newInsert(Driver.CONTENT_URI).withValues(driverv)
.withValueBackReference(Driver.DRIVER_CAR_FK, 0).build());
//... applyBatch etc.
如果我省略了carv.putBaseColumns.\u ID,0,它将不起作用。如果我保留它,我必须设置自动递增将分配的值。驱动程序。\u ID被设置为主键
所以我的问题是,
如何让CARS行设置自己的_ID,并在插入DRIVER时在批的第二次插入中引用该ID
非常感谢您的帮助,文档不是很清楚 这可能太晚了,帮不上忙,但你似乎有正确的想法。从您的示例来看,您的db命名方案有点混乱。您不需要carv.putBaseColumns.\u ID,0;因为数据库应该为您创建此值。您也不需要将driverv.putDriver.DRIVER\u CAR\u FK设置为0;虽然这不会造成伤害-根据值,返回引用优先。如果仍然存在问题,那么可能是因为数据库中外键的设置方式
ArrayList<ContentProviderOperation> opList = new
ArrayList<ContentProviderOperation>();
ContentValues carv = new ContentValues();
carv.put(Car.CAR_MAKE, carData.make);
carv.put(Car.CAR_MODEL, carData.model);
opList.add(ContentProviderOperation.newInsert(Car.CONTENT_URI).withValues(carv).build());
ContentValues driverv = new ContentValues();
driverv.put(Driver.DRIVER_NAME, carData.driverName);
opList.add(ContentProviderOperation.newInsert(Driver.CONTENT_URI)
.withValues(driverv)
.withValueBackReference(Driver.DRIVER_CAR_FK, 0).build());