是否可以在没有主键的情况下在 Room 中创建 table?

Is it possible to create a table in the Room without a primary key?

我在 MySql 中有一个 table,我将其命名为 FAQs,在 table 中,有两列,Question columnAnswer column,我想获取 FAQs table 中的数据并将其存储在离线数据库中,但我收到此消息 An entity must have at least 1 field annotated with @PrimaryKey

Table

@Entity(tableName = "FAQs")
public class FAQModel {
    
    private String question, answer;

    public String getQuestion() {
        return question;
    }

    public String getAnswer() {
        return answer;
    }

}

是否可以在没有主键的情况下在 Room 中创建一个 table?

是的,你可以,但有一些困难,但不是通过房间注释,即使它仍然有一个主键,所以答案是否定的。

  • 可以(例如通过回调)创建一个似乎没有主键列的 table,例如CREATE TABLE IF NOT EXISTS the_table (question TEXT, answer TEXT)然而,
    • 它在通常隐藏的 rowid 列上有一个主键。
    • 这样的 table 将无法轻易使用,因为您必须避免 Room 的编译时间 SQL 语句检查。
    • 您也不能直接利用 Room 的底层 table to/from 对象处理。

然而,你发表评论

But in the android app I only get the question and answer column and I am not getting faqId because I don't want to use it inside my app.

所以您可以有一个排除 faqId 列的 POJO class,例如

class FAQModelLessIdColumn {
    String question,answer;
}

假设 FAQModel 是实体,因此是 tablename,那么根据上面的内容,您可以有一个 @Query,例如:-

@Query("SELECT * FROM faqmodel")
abstract List<FAQModelLessIdColumn> getFAQModelsLessTheFaqIdColumn();

但是,随着时间的推移,您可能会了解到主键列非常有用,因为它必须 唯一标识 table 中的单个行。因此,您可以从单个值高效地执行 CRUD 操作。

  • 作为类比,将 table 视为一个列表,其中的问题没有按特定顺序写下。要找到一个问题及其答案 闰年有多少天 那么您必须搜索整个列表,直到找到问题。但是,如果根据问题的第一个字符将列表分成多个列表,并且这些列表按顺序维护,那么跳到 H 列表可能会使问题更容易找到。因此索引可以大大减少搜索时间。因此,拥有可用的 faqId 可以通过主索引进行搜索,而且速度会更快。