多个表同一个对象房间(多语言数据库) [英] Room multiple tables same Object (multi language database)
问题描述
我正在一个android项目中工作,该项目必须在本地DB(Room)中存储一些数据.我必须提供的功能之一是将数据以不同的语言存储在本地数据库中,例如,如果我有食品信息,则该信息必须以英语,德语,法语等存储.
I am working on an android project where have to store some data in the local DB (Room). One of the functionality which I have to provide is to store the data in the local DB in different languages, for example if I have information for food, this information has to be stored in English, German, French and so on.
我的数据库的结构是这样的:
The structure of my DB is something like that:
@Entity(tableName = "food")
public class Food{
}
@Entity(tableName = "food_fr")
public class FoodFr{
}
@Entity(tableName = "food_de")
public class FoodDe{
}
我的问题是,如何让这三个不同的表(使用不同的语言)具有相同的列,并且@Dao对象为所有它们返回一个公共(父)对象?
My question is how I can have these three different tables (on different languages) with same columns and the @Dao object return one common (parent) object for all of them?
我完全不确定这是否有可能,但是如果有人对这种情况有解决方案,请提供帮助.
I am not really sure that is possible at all, but if someone has a solution for that case, please help.
先谢谢您了:)
推荐答案
最好的解决方案是只有一个表,而不是三个表.使用一列来区分三种语言(例如,具有en
,fr
和de
值的language
列).由于无论如何您都会重写许多现有代码,因此从三个表切换到一个表似乎并不是主要障碍.
The best solution is to have a single table, rather than three tables. Use a column to distinguish between the three languages (e.g., a language
column with en
, fr
, and de
values). Since you will be rewriting much of your existing code anyway, switching from three tables to one would not seem to be a major impediment.
话虽这么说,为了保留现有的三表结构,将Food
,FoodFr
和FoodDe
都从一个通用的基类(例如,BaseFood
)中扩展,您可以在其中定义字段/列.
That being said, to keep your existing three-table structure, have Food
, FoodFr
, and FoodDe
all extend from a common base class (e.g., BaseFood
), where you define your fields/columns.
对于查询,您需要让DAO处理所有四种情况(三种特定的语言表,以及一种将三种三种结果组合在一起的方法),例如:
For queries, you would need to have your DAO handle all four cases (three specific language tables, plus a method to combine the results for all three), such as:
@Query("SELECT * FROM Food")
List<Food> getAllFood();
@Query("SELECT * FROM FoodFr")
List<FoodFr> getAllFrenchFood();
@Query("SELECT * FROM FoodDe")
List<FoodDe> getAllGermanFood();
@Transaction
List<BaseFood> getAllFoodAcrossAllThreeLanguages() {
ArrayList<BaseFood> result=new ArrayList<>();
result.addAll(getAllFood());
result.addAll(getAllFrenchFood());
result.addAll(getAllGermanFood());
return result;
}
这篇关于多个表同一个对象房间(多语言数据库)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!