Return 列子集的房间查询错误

Error in Room Query to Return Subset of Columns

我在玩 Room,但找不到解决我的问题的方法。

下面是数据。

Table

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

Table数据

实体

@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]

如果我在 Query 2 上面添加 id,它会起作用。

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

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

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

房间版 1.1.1

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

I think you should include in
@ColumnInfo(name = "id") @PrimaryKey private int id;

because as per the error thrown there is no such column existing as id in your entity by the above query, first the column id is referred as match of the tables column id and then set a primary key via annotation

对于来自多个字段的 select 数据,请考虑以下示例。

来自文档

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();
}

添加到@karan 的回答中,pojo 还可以用于使用 as 子句

的 return 命名列

例如

select sum(score) as total_score, sum(avg) as avg_score from mytable

其中 pojo class 列名称分别为 total_score 和 avg_score ..