根据文档here“实体或道类的数量没有限制,但它们在数据库中必须是唯一的。”所以我认为您可以简单地在扩展RoomDatabase 的数据库类中声明不同的类。
您是否尝试过简单地将不同的 POJO 声明为不同的实体并将它们全部包含在同一个数据库类中?
例如:
// Article, Topic and Media are classes annotated with @Entity.
@Database(version = 1, entities = {Article.class, Topic.class, Media.class})
abstract class MyDatabase extends RoomDatabase {
// ArticleDao is a class annotated with @Dao.
abstract public ArticleDao articleDao();
// TopicDao is a class annotated with @Dao.
abstract public TopicDao topicDao();
// MediaDao is a class annotated with @Dao.
abstract public MediaDao mediaDao();
}
这可能对冗余没有帮助,但我最初的想法也是类型转换器。实际上,我什至使用TypeConverters 和单个Dao 成功地将parcelable 对象作为我的Room Database 中的列实现。
您是否尝试过在您的TypeConverter 课程中使用Gson?我相信this article 更直接地解决了您的问题。它是在房间数据库中存储对象的指南。同样,诀窍在于类型转换器并将您的对象声明为 Gson 的类型标记。例如:
public class Converters {
@TypeConverter
public static List<Media> fromStringToList(String mediaListString) {
Type myType = new TypeToken<List<Media>>() {}.getType();
return new Gson().fromJson(mediaListString, myType);
}
@TypeConverter
public static String fromMediaListToString(List<Media> mediaItems) {
if (mediaItems== null || mediaItems.size() == 0) {
return (null);
}
Gson gson = new Gson();
Type type = new TypeToken<List<VideoParcelable>>() {
}.getType();
String json = gson.toJson(mediaItems, type);
return json;
}
}
这解决了您尝试过的事情。现在开始您的陈述“我相信我需要将对象转换为与数据库实体模型匹配的对象。”其实,不一定。您可以将@Ignore 注解用于您的实体的不同创建实例或实现,只要至少有一个默认构造函数包含entry 的primary key。在你的情况下:
@Entity(foreignKeys = {
@ForeignKey(entity = Article.class, parentColumns = "id", childColumns =
"articleId"),
@ForeignKey(entity = Topic.class, parentColumns = "id", childColumns =
"topicId"),
@ForeignKey(entity = Media.class, parentColumns = "id", childColumns =
"mediaId")
}
public class ArticlesEntry {
@PrimaryKey
public Long articleId;
@ColumnInfo(name = "topic_id")
public Long topicId;
@ColumnInfo(name = "media_id")
public Long mediaId;
private Article articleObject;
private Media mediaObject;
//default constructor
public ArticlesEntry(int id) {
this.articleId = id;
}
//You can call this anytime you add to the database with media object input
@Ignore
public ArticlesEntry(int id, Media inMedia) {
this.articleId = id;
this.mediaObject= inMedia;
}
//You can create many of these and insert as needed, the left out variables of the
//are null, note that id has to be passed b/c your primary key isn't set to
//autogenerate
@Ignore
public ArticlesEntry(int id, Article inArticle) {
this.articleId = id;
this.articleObject= articleObject;
}
//Or both objects:
@Ignore
public ArticlesEntry(int id, Media inMedia, Article inArticle) {
this.articleId = id;
this.mediaObject = inMedia;
this.articleObject= articleObject;
}
//getters and setters here...
}
如果您像上面一样创建ArticlesEntry,则需要创建并包含不同的TypeConverters,它们都可以在同一个类中并使用@TypeConverters(MyConverters.class) 导入到特定的数据库中。希望这会有所帮助!