Android 结点值的房间子集

Android Room subset of values from a junction

我正在尝试从结点 table 中提取 values/columns 的一个子集,如下所示

@Entity
class Conversation {

    @PrimaryKey
    @ColumnInfo(name = "id")
    @NonNull
    String id = UUID.randomUUID().toString();

}

@Entity
class User {

    @PrimaryKey
    @ColumnInfo(name = "id")
    int id;

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

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

    @ColumnInfo(name = "image")
    String image;

}

class SimpleUser {

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

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

}

@Entity(
    primaryKeys = {"conversation_id", "user_id"},
    foreignKeys = {
        @ForeignKey(
            entity = Conversation.class,
            parentColumns = "id",
            childColumns = "conversation_id"
        ),
        @ForeignKey(
            entity = User.class,
            parentColumns = "id",
            childColumns = "user_id"
        )
    },
    indices = {
        @Index("conversation_id"),
        @Index("user_id")
    }
)

class ConversationUser {

    @ColumnInfo(name = "conversation_id")
    @NonNull
    String conversationId = UUID.randomUUID().toString();

    @ColumnInfo(name = "user_id")
    int userId;

}

class ConversationSimpleUserList {

    @Relation(
        parentColumn = "conversation_id",
        entityColumn = "id",
        associateBy = @Junction(
            value = ConversationUser.class,
            parentColumn = "conversation_id",
            entityColumn = "user_id"
        ),
        projection = {
            "first_name", "last_name"
        }
    )
    List<SimpleUser> simpleUserList; <- I want users without all the fields I will not be using

}

但是它抛出以下错误:

Cannot find the child entity column `id` in SimpleUser

这不可能吗?我找不到任何说明如何执行此类操作的文档或示例。

您是否尝试过在 Relation 中明确使用实体 class 名称?

由于 Room 在 SimpleUser class 中找不到 id 字段 - 但在基础 User class 中有这样一个字段:

class ConversationSimpleUserList {
.....
    @Relation(
        entity = User.class,  // <-- explicitly added entity
        parentColumn = "conversation_id",
        entityColumn = "id",
        associateBy = @Junction(
.........
   
}