I have 2 entities:
@Entity(tableName = "author")
data class Author(
@PrimaryKey
@ColumnInfo(name = "id")
val id: String,
@ColumnInfo(name = "name")
val name: String
)
data class Book(
@ColumnInfo(name = "id")
val id: String,
@ColumnInfo(name = "title")
val title: String,
@ColumnInfo(name = "author_id")
var authorId: String
)
And I would like to join them in a query:
@Query("SELECT * FROM book JOIN author ON author.id = book.author_id AND author.id = :authorId WHERE book.id = :bookId")
fun item(authorId: String, bookId: String): LiveData<BookWithAuthor>
Into this entity:
@Entity
data class BookWithAuthor(
@Relation(parentColumn = "author_id", entityColumn = "id")
val author: Author,
@Embedded
val book: Book
)
However when I do that I get back a BookWithAuthor object in which the author.id and book.id are the same id, in this case they are both the author's id. How do I deconflict the "id" property in the entities in the "join" object?
You can use the @Embedded's
prefixto disambiguate the names.e.g. use :-
along with :-
You would then change BookWithAuthor to use the prefixed column so :-
However, your comment it assumes that all book ids are unique. In my case I could potentially have duplicate book ids for different authors.
appears to not fit in with the table/entities (schema) you have coded. i.e.
entities=[....]lis. The assumption made is that the id is/would be the primary key and annotated accordingly and thus unique.@Relationshipannotation in an Entity that is defined as an Entity to the database (i.e. one of the classes in theentities=[....]list of the@Databaseannotation).So unless the primary key of the Book entity/table is not the id or that the authorid is a list of authors then a Book can have only one author. As such it would appear that you only need
@Query("SELECT * FROM book WHERE id=:bookId"): LiveData<BookWithAuthor>I suspect that what you want is that a book can have a number of authors and that an author can be an author of a number of books. In this scenario you would typically use a mapping table (can be called other names such as link, reference, associative .... ). If this is the case and you can't ascertain how to create the mapping table via room, then you could ask another question in that regard.