交界处的Android Room值子集

问题描述

我正尝试从联结表中提取值/列的子集,如下所示:

@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,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中显式使用实体类名称?

由于Room在id类中找不到SimpleUser字段-但在基础User类中却存在这样的字段:

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