我过去的大部分项目都使用 SugarDB。它易于使用并满足了我的大部分要求,但由于该项目已被放弃,我决定寻找替代方案,而 Room 似乎是最佳选择。
然而,一些基本的东西在 Room 中是相当困惑的。我的对象使用 Gson 填充来自网络服务的数据,以及指向其他对象的链接。例如,考虑以下类:
@Entity
public class TestModel
{
@PrimaryKey(autoGenerate = true)
private int id;
private String name;
private String age;
private List<Book> issuedBooks;
}
public class Book
{
private String title;
private int ISBN;
}
现在,如果我的第一个类被注释为实体,这会自动将其中引用的类也视为实体吗?
如果我保存一个 TestModel 对象,它会把 Books 列表和它一起保存到数据库吗?
最佳答案
我想你可以这样做。
@Entity
public class TestModel {
@PrimaryKey
public int id; // TestModel id
public String name;
public String age;
}
@Entity
public class Book {
@PrimaryKey
public int id; // Book id
public int testModelId; // TestModel id
public String title;
public int ISBN;
}
public class TestModelWithBooks {
@Embedded
public TestModel testModel;
@Relation(parentColumn = "id", entityColumn = "testModelId", entity = Book.class)
public List<Book> books;
}
对于他们的Dao
,可以这样写。
@Dao
public interface TestModelDao {
@Query("SELECT * FROM TestModel")
public List<TestModelWithBooks> loadTestModelsWithBooks();
}
关于android - Room 中的一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48443760/