首页 > 解决方案 > 与我的数据库的单个列一起使用的查询错误

问题描述

我正在使用带有 Room 库的 Android 架构组件。基本上我想从两个不同查询中的两个单独列中获取结果。如果有人可以帮助或建议我如何系统化我的实体,我会很高兴,谢谢。

@Entity(tableName = "note_table")
public class Note {

    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "id_col")
    private int id;

    @Ignore
    @ColumnInfo(name = "checks_col")       
    private ArrayList<Checks> checks = new ArrayList<>();

    @ColumnInfo(name = "res_col")
    private String result;

    public Note(String result, ArrayList<Checks> checks) {
        this.checks = checks;
        this.result = result;
    }

    public void setId(int id) {this.id = id;}
    public int getId() {return id;}
    public void setResult(String result){this.result = result;}
    public String getResult() {return result;}
    public void setChecks(ArrayList<Checks> checks){this.checks = checks;}
    @TypeConverters({Converters.class})
    public ArrayList<Checks> getChecks() {return checks;}

}
@Dao
public interface NoteDao {

    @Insert
    void insert(Note note);

    @Update
    void update(Note note);

    @Delete
    void delete(Note note);

    @Query("DELETE FROM note_table")
    void deleteAllNotes();

    @Query("SELECT * FROM note_table")
    LiveData<List<Note>> getAllNotes();

    @Query("SELECT res_col FROM note_table ORDER BY res_col DESC LIMIT 1 ") // <-- this is my try //
    LiveData<Note> getResultNote();

}

错误如下:

The columns returned by the query does not have the fields [id] . Even though they are annotated as non-null or primitive. Columns returned by the query: [res_col]

警告信息如下:

Note has some fields [id_col] which are not returned by the query. If they are not supposed to be read from the result, you can mark them with @Ignore annotation. You can suppress this warning by annotating the method with @SuppressWarnings(RoomWarnings.CURSOR_MISMATCH). Columns returned by the query: res_col. Fields in Note: id_col, res_col.

标签: androiddatabaseandroid-sqliteandroid-roomdao

解决方案


LiveData<Note> getResultNote();

想要返回一个Note对象,因为某些列被注释或暗示为非空(即private int id;intJava 原语,那么它不能为空) ,则无法为查询返回的字符串构建Note 。

您想getResultNote()返回String而不是Note

交替使用SELECT * .....而不是SELECT res_col ......返回 Note ,然后从Note获取字符串。


推荐阅读