java从Room数据库中的模型对象存储什么
我有三节POJO课Recipe
、Ingredient
和Step
我希望能够在离线时浏览我的食谱,所以我决定使用Room
食谱。班级
@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
...
转换器。班级
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);
}
}
往复式数据库。班级
@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;
}
}
回复。班级
@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
之后,我是否还应该保存我的每个步骤的数据库。分类和成分。类?我是否也应该为这些类包含@Entity
注释?我应该做一个StepDatabase
和一个IngredientDatabase
吗?离线时也需要访问我的Recipes
吗
# 1 楼答案
是的,在我看来,首先为每个表声明一个模型是一个很好的做法,是的,每个模型都应该包含@Entity注释,告诉hibernate您映射的是来自数据库的一个表