注释Android房道的正确方法?

Proper Way to annotate Android Room Dao?

我按照 Codelab 教程进行了操作,结果却一头雾水。我想使用外部数据库进行测试,唯一的 table 和列(word_tableword 如前所述在代码实验室中)工作正常。但我正在尝试使用以下 sql 信息添加我自己创建的 .db:

CREATE TABLE "product_table" (
    "id"    INTEGER NOT NULL,
    "product"   TEXT,
    "partof"    TEXT,
    PRIMARY KEY("id")
);

我不确定如何正确注释它。以下是我正在使用的代码。

WordDao.kt

@Dao
interface WordDao {

@Query("SELECT * from product_table ORDER BY id ASC")
fun getAlphabetizedId(): List<Id>

@Query("SELECT * from product_table ORDER BY word ASC")
fun getAlphabetizedWords(): LiveData<List<Word>>

@Query("SELECT * from product_table ORDER BY partof ASC")
fun getAlphabetizedPartof(): List<Partof>

Product.kt

@Entity(tableName = "eilian_table")
class Id(@PrimaryKey @ColumnInfo(name = "id") val id: String)

@Entity(tableName = "eilian_table")
class Word(@ColumnInfo(name = "word") val word: String)

@Entity(tableName = "eilian_table")
class Partof(@ColumnInfo(name = "partof") val partof: String)

获取符号和引用错误。

查看 the docs - 基本上 Entity 代表 table,您正在为相同的 table 创建三个,每个都有一个字段.这是你的 SQL:

CREATE TABLE "product_table" (
    "id"    INTEGER NOT NULL,
    "product"   TEXT,
    "partof"    TEXT,
    PRIMARY KEY("id")
);

所以你想要这样的东西:

@Entity(tablename = "product_table")
data class Product(
    @PrimaryKey
    val id: Int,
    val product: String,
    @ColumnInfo(name = "partof")
    val partOf: String
)

并且您可以看到它基本上是如何映射到 SQL - 您可能希望使 String 可以为 null,并且我加入了 @ColumnInfo 注释作为示例Kotlin 字段名称与 table 中的列名称不同的地方(即使它是 case-insensitive 所以在这里实际上并不重要)。

您需要更改查询,以便仅从 table

中提取所需的列