我正在为Sqlite - Room试用新的Android架构组件。我试图将它与存储库模式一起使用,这样如果我没有将信息存储在本地数据库中,我可以将它从云中拉出来。
我有两个表 - Person和MovieCast,其中MovieCast表有一个指向Person表的外键。当我从API中提取数据时,我从一个API调用中获取所有内容,因此我想首先在Person表中插入所有人,这样我就可以将电影转换数据插入到MovieCast表中而不会得到a"外键约束失败"例外。我似乎无法弄清楚这样做的方式,因为插入任务是异步的,而且当插入完成时,Room似乎没有发回任何信号。
这是我试图开始工作的代码,我知道将一个插件放在另一个插件后不会起作用,但这就是我所拥有的。<\ n \ n
/ p>public LiveData<List<MovieCastEntity>> getMovieCastByMovieId(int id) {
movieAPI.getMovieCredits(id).enqueue(new Callback<Credits>() {
@Override
public void onResponse(@NonNull Call<Credits> call, @NonNull Response<Credits> response) {
personDao.insertAll(Mapper.MapFromAPICastListToPersonEntityList(response.body().getCast()));
movieCastDao.insertAll(Mapper.MapFromAPICastToMovieCastEntity(response.body().getCast(), id));
}
@Override
public void onFailure(@NonNull Call<Credits> call, @NonNull Throwable t) {
}
});
return movieCastDao.getMovieCastByMovieId(id);
}
这些是Mapper方法。
public static List<MovieCastEntity> MapFromAPICastToMovieCastEntity(List<Cast> cast, int mvId) {
List<MovieCastEntity> list = new ArrayList<>();
for (Cast c : cast) {
list.add(new MovieCastEntity() {
{
personId = c.getId();
movieId = mvId;
character = c.getCharacter();
}
});
}
return list;
}
public static List<PersonEntity> MapFromAPICastListToPersonEntityList(List<Cast> cast) {
List<PersonEntity> list = new ArrayList<>();
for (Cast c : cast) {
list.add(new PersonEntity() {
{
id = c.getId();
name = c.getName();
profilePath = c.getProfilePath();
}
});
}
return list;
}
这些是我的实体。
MovieCastEntity
@Entity(tableName = "movie_cast", foreignKeys = {
@ForeignKey(
entity = MovieEntity.class,
parentColumns = "id",
childColumns = "movieId",
onDelete = ForeignKey.CASCADE,
onUpdate = ForeignKey.CASCADE
),
@ForeignKey(
entity = PersonEntity.class,
parentColumns = "id",
childColumns = "personId",
onDelete = ForeignKey.CASCADE,
onUpdate = ForeignKey.CASCADE
)
}, indices = {
@Index("movieId"),
@Index("personId")
})
public class MovieCastEntity {
@PrimaryKey(autoGenerate = true)
public long id;
public long personId;
public long movieId;
public String character;
}
PersonEntity
@Entity(tableName = "person")
public class PersonEntity {
@PrimaryKey
public long id;
public String name;
public String profilePath;
}
插入方法只是使用@Insert注释。