我正在使用Room库在我的Android应用程序中持久化数据。我有两个主要的表,即任务和组。它们之间是一对多的关系,一个任务只能属于一个组,但一个组可以属于多个任务。
持久性工作正常,但问题是当我尝试从一个组更新信息时,与该组相关的所有任务都被删除。
以下是我的实体和DAO配置:
任务实体
@Entity(tableName = "task",
foreignKeys = {
@ForeignKey(
entity = Group.class,
parentColumns = "id",
childColumns = "groupId",
onDelete = CASCADE,
onUpdate = RESTRICT
)},
indices = {@Index(value = "id"), @Index(value = "groupId")}
)
public class Task {
@PrimaryKey(autoGenerate = true)
private int id;
private String name;
private int groupId;
public Task(int id, String name, int groupId) {
this.id = id;
this.name = name;
this.groupId = groupId;
}
}
群体实体
@Entity(tableName = "group")
public class Group {
@PrimaryKey(autoGenerate = true)
private int id;
private String name;
public Group(int id, String name) {
this.id = id;
this.name = name;
}
}
任务DAO
@Dao
public interface TaskDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
void addTask(Task task);
@Query("select * from task")
public List<Task> listAllTasks();
@Query("select * from task where id = :taskId")
public Task getTask(int taskId);
@Update(onConflict = OnConflictStrategy.REPLACE)
void updateTask(Task task);
@Query("delete from task")
void removeAllTasks();
@Delete
void delete(Task task);
}
群组DAO
@Dao
public interface GroupDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
void addGroup(Group group);
@Query("select * from `group`")
public List<Group> listAllGroups();
@Query("select * from `group` where id = :groupId")
public Group getGroup(long groupId);
@Update(onConflict = OnConflictStrategy.REPLACE)
void updateGroup(Group group);
@Query("delete from `group`")
void removeAllGroups();
@Delete
void delete(Group group);
}
在任务类中实体声明中将 OnUpdate 更改为 RESTRICT、CASCADE 或 NO_ACTION 并不起作用。
我将非常感激任何帮助。谢谢。