【发布时间】:2018-01-20 14:04:01
【问题描述】:
我有 3 个 POJO 课程。 Recipe、Ingredient 和 Step。
我希望能够在离线时浏览我的食谱,所以我决定使用Room。
Recipe.class
@Entity(tableName = "recipe")
public class Recipe implements Parcelable {
@PrimaryKey(autoGenerate = false)
@SerializedName("id")
public int recipeId;
@ColumnInfo(name = "recipe_name")
public String name;
@TypeConverters(Converters.class)
public List<Ingredient> ingredients = null;
@TypeConverters(Converters.class)
public List<Step> steps = null;
@ColumnInfo(name = "recipe_servings")
public int servings;
@Ignore
public String image;
public Recipe(int recipeId, String name, List<Ingredient> ingredients, List<Step> steps, int servings, String image) {
this.recipeId = recipeId;
this.name = name;
this.ingredients = ingredients;
this.steps = steps;
this.servings = servings;
this.image = image;
}
...
//getters and setters
...
Converters.class
public class Converters {
static Gson gson = new Gson();
@TypeConverter
public static List<Ingredient> stringToIngredientList(String data) {
if (data == null) {
return Collections.emptyList();
}
Type listType = new TypeToken<List<Ingredient>>() {}.getType();
return gson.fromJson(data, listType);
}
@TypeConverter
public static String ingredientListToString(List<Ingredient> ingredients) {
return gson.toJson(ingredients);
}
@TypeConverter
public static List<Step> stringToStepList(String data) {
if (data == null) {
return Collections.emptyList();
}
Type listType = new TypeToken<List<Step>>() {}.getType();
return gson.fromJson(data, listType);
}
@TypeConverter
public static String stepListToString(List<Step> steps) {
return gson.toJson(steps);
}
}
RecipeDatabase.class
@Database(entities = {Recipe.class}, version = 1)
abstract class RecipeDatabase extends RoomDatabase {
private static RecipeDatabase INSTANCE;
public abstract RecipeDao recipeDao();
public static RecipeDatabase getRecipeDatabase(Context context) {
if (INSTANCE == null) {
INSTANCE =
Room.databaseBuilder(context.getApplicationContext(), RecipeDatabase.class, "recipe-database")
// allow queries on the main thread.
// Don't do this on a real app! See PersistenceBasicSample for an example.
.allowMainThreadQueries()
.build();
}
return INSTANCE;
}
public static void destroyInstance() {
INSTANCE = null;
}
}
RecipeDao.class
@Dao
public interface RecipeDao {
@Query("SELECT * FROM recipe")
List<Recipe> getAll();
@Query("SELECT * FROM recipe where recipe_name LIKE :name")
Recipe findByName(String name);
@Query("SELECT COUNT(*) from recipe")
int countRecipes();
@Update
void update(Recipe... recipes);
@Insert
void insertAll(Recipe... recipes);
@Delete
void delete(Recipe recipe);
}
我的问题:在使用 Converters 类将 List<Step> 和 List<Ingredient> 保存为 Strings 之后,我是否还应该保存我的每个 Step.class 和 的数据库>Ingredient.class?我是否也应该为这些类添加 @Entity 注释?我应该创建一个StepDatabase 和一个IngredientDatabase 吗?离线时是否也需要能够访问我的Recipes?
【问题讨论】:
标签: java android database pojo android-room