android - 房间数据库 : What is Index specific columns (indices and @Index) and how to use it?

标签 android android-room android-architecture-components

我指的是房间数据库的索引特定列。

下面是这里写的一些示例代码https://developer.android.com/training/data-storage/room/defining-data#column-indexing

示例代码-1:

    @Entity(indices = {@Index("name"),
        @Index(value = {"last_name", "address"})})
public class User {
    @PrimaryKey
    public int id;

    public String firstName;
    public String address;

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

    @Ignore
    Bitmap picture;
}

示例代码 2:

@Entity(indices = {@Index(value = {"first_name", "last_name"},
        unique = true)})
public class User {
    @PrimaryKey
    public int id;

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

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

    @Ignore
    Bitmap picture;
}

这在 android 的房间文档中有描述, 我已经使用索引来保证列的唯一性,但是上面的代码意味着什么,有人能解释一下吗?

Q1:indices和@Index有什么用?
Q2:@Index("name")@Index(value = {"last_name", "address"})有什么区别?

最佳答案

回答有点晚了。但希望它能对某人有所帮助。

Q1:indices@Index有什么用?

Indices: 可以包含表中的索引列表。而 @Index 用于定义一个索引

例如:

@Entity(indices = {
    @Index("FirstIndex"),@Index(value="last_name",unique = true),
    @Index("SecondIndex"),@Index(value="first_name", unique = true)
})

正如你所看到的,我在这个例子中定义了两个索引,用逗号分隔。这里“FirstIndex”和“SecondIndex”是索引的名称。如果我没有定义索引的名称(正如您在示例中引用的那样),那么 Room 会将其设置为由“”连接并以“index${tableName}”为前缀的列列表.因此,如果您有一个名称为“Foo”且索引为 {"bar", "baz"} 的表,则生成的索引名称将为“index_Foo_bar_baz”。

问题 2:@Index("name")@Index(value = {"last_name", "address"}) 有什么区别?

@index("name") //syntax to give name of index.
@index(value=last_name", "address") //Syntax to define, which column(s) need to be indexed

关于android - 房间数据库 : What is Index specific columns (indices and @Index) and how to use it?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54886250/

相关文章:

Android 用例单元测试

android - android:gradle:依赖版本相同

android - 使用 Android volley 进行单元测试

java - 是否可以将同一个对象保存到两个不同的表房间?

android - 房间 : related entities - usable public constructor

java - 从 arraylist 和 hashmap 中删除重复项

java - 执行 get 时 Room DB 正在更改项目的顺序

android - 当我想在 Room 中存储数据时 NOT NULL 约束失败

android - 我们应该使用 lambda 还是匿名类来观察 LiveData

android - 为什么我的 pagedList 没有通过 LiveData 方法 .observe 更新?