首页 > 解决方案 > 如何在房间数据库中查询使用类型转换器保存的数组中的整数?

问题描述

我正在使用类型转换器在我的房间数据库中保存一个列表。现在我想查询数据库并检索列表包含特定整数的对象。例如:对象 1 列表包含整数 1、2、3,当我仅查询整数 1 时,它会检索对象 1。

这是我正在尝试的:我的实体:

@Entity(tableName = "exercises")
public class Exercise {

    @PrimaryKey(autoGenerate = true)
    private int id;
    @ColumnInfo(name = "api_id")
    private int apiId;
    @ColumnInfo(name = "exercise_name")
    private String exerciseName;
    @ColumnInfo(name = "image_path")
    private String imagePath;
    @ColumnInfo(name = "youtube_key")
    private String youtubeKey;
    @ColumnInfo(name = "exercise_type")
    private int exerciseType;
    @ColumnInfo(name = "muscle_group")
    private List<Integer> muscleGroup;
    @ColumnInfo(name = "secondary_muscles")
    private List<Integer> secondaryMuscles;
    @ColumnInfo(name = "notes")
    private String notes;

我的类型转换器:

@TypeConverter
    public static String fromList(List<Integer> list){
        Gson gson = new Gson();
        String json = gson.toJson(list);
        return json;
    }

    @TypeConverter
    public static List<Integer> fromString(String string){
        Type listType = new TypeToken<List<Integer>>() {}.getType();
        return new Gson().fromJson(string, listType);
    }

我的道:

@Query("SELECT * FROM exercises WHERE muscle_group LIKE :muscle")
    LiveData<List<Exercise>> getByMuscle(List<Integer> muscle);

我的视图模型:

private LiveData<List<Exercise>> exercises;

    public LiveData<List<Exercise>> getExercises(Context context, int muscleGroup){
        if(exercises == null){
            loadData(context, muscleGroup);
        }
        return exercises;
    }

    private void loadData(Context context, int muscleGroup){
        List<Integer> muscle = Arrays.asList(muscleGroup);
        AppDatabase db = AppDatabase.getInstance(context);
        Log.d(TAG, "Load data from database");
        exercises = db.exerciseDao().getByMuscle(muscle);
    }
    

有人知道我想要的是否可行?还是我需要做一个像检索所有而不是在for循环中选择的工作?感谢您的投入。

标签: javaandroiddatabaseandroid-room

解决方案


推荐阅读