我在玩 Room,但我找不到解决我的查询的方法。
下面是数据。
表格
CREATE TABLE `Employee` (
`id` INTEGER NOT NULL,
`first_name` TEXT,
`last_name` TEXT,
PRIMARY KEY(`id`)
);
表格数据
实体
@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 Key
和 Foreign Key
列时出现错误。
问题 1
这是否意味着我们必须始终包含 Primary Key
和 Foreign 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/