我有2个实体类:
@Entity(tableName = "work_orders")
public class WorkOrderEntity
{
@PrimaryKey(autoGenerate = true)
private long id;
...
}
@Entity(tableName = "activity_logs", foreignKeys = {
@ForeignKey(entity = WorkOrderEntity.class, parentColumns = "id", childColumns = "work_order_id") })
public class ActivityLogEntity
{
@PrimaryKey(autoGenerate = true)
private long id;
@ColumnInfo(name = "work_order_id")
private long workOrderId;
...
}
有没有办法在一个事务中的work_orders和activity_log表中插入记录?像这样:
@Transaction
public void insertBoth(WorkOrderEntity workOrderEntity, ActivityLogEntity activityLogEntity)
{
insertWorkOrder(workOrderEntity);
insertActivityLog(activityLogEntity);
}
考虑到外键约束。
以下是类似问题Insert into multiple tables using Room Persistence Library,但没有详细解答
答案 0 :(得分:2)
我想出了这个解决方案:
@Transaction
public void insertBoth(WorkOrderEntity workOrderEntity, ActivityLogEntity activityLogEntity)
{
long workOrderId = insertWorkOrder(workOrderEntity);
activityLogEntity.setWorkOrderId(workOrderId);
insertActivityLog(activityLogEntity);
}