android - 返回列子集的房间查询错误

标签 android android-sqlite android-room android-architecture-components

我在玩 Room,但我找不到解决我的查询的方法。

下面是数据。

表格

CREATE TABLE `Employee` (
    `id` INTEGER NOT NULL,
    `first_name` TEXT,
    `last_name` TEXT,
    PRIMARY KEY(`id`)
);

表格数据

enter image description here

实体

@Entity(tableName = "Employee")
public class Employee {

    @PrimaryKey
    private int id;

    @ColumnInfo(name = "first_name")
    private String firstName;

    @ColumnInfo(name = "last_name")
    private String lastName;

    ..Getters & Setters..
}

查询 1

@Query("Select * from Employee")
List<Employee> getEmployees();

结果 成功了

查询 2

@Query("Select first_name, last_name from Employee")
List<Employee> getEmployees();

结果

error: The columns returned by the query does not have the fields [id] in ***.Employee even though they are annotated as non-null or primitive. Columns returned by the query: [first_name, last_name]

如果我将 id 添加到上面的 Query 2 中,它会起作用。

同样,如果我们在表中有一个外键并且我们尝试查询列的子集,它会抛出错误。当我们在查询中同时添加 Primary KeyForeign Key 列时出现错误。

问题 1 这是否意味着我们必须始终包含 Primary KeyForeign Key (如果存在)在查询中?

问题 2 它抛出这样的错误的背后到底发生了什么?还是我做错了什么?

房间版 1.1.1

另外,提到这个link但它并没有解决我的主键问题。

最佳答案

要从多个字段中选择数据,请考虑以下示例。

来自文档

Room allows you to return any Java-based object from your queries as long as the set of result columns can be mapped into the returned object. For example, you can create the following plain old Java-based object (POJO) to fetch the user's first name and last name:

public class NameTuple {
    @ColumnInfo(name = "first_name")
    public String firstName;

    @ColumnInfo(name = "last_name")
    public String lastName;
}

现在,您可以在查询方法中使用此 POJO:

@Dao
public interface MyDao {
    @Query("SELECT first_name, last_name FROM user")
    public List<NameTuple> loadFullName();
}

关于android - 返回列子集的房间查询错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53437176/

相关文章:

android - clearAllTables 不起作用

android - 如何通过单击按钮删除房间的 SQlite 行

java - 返回 List<Object> 的房间查询会卡住应用程序

android - 如何在 View 上绘制边框和分隔符

android-sqlite - 通过从断言复制数据库文件在 Room 中使用预填充的数据库

android - 在android中存储配置

android - 如何在 onCreate() 之外使用 ViewModel?

android - 单击 RecyclerView 中选中的项时设置项的状态

android - GMail 中的 ListView 行标记

android - 动态数组输入