How can we query all entities with their one to many relationship with Room?
Say we have a User Entity :
@Entity
class User(@PrimaryKey(autoGenerate = true) var id: Long?, var name: String)
and a Pet Entity :
@Entity(foreignKeys = [(ForeignKey(entity = User::class,
parentColumns = ["id"],
childColumns = ["userId"],
onDelete = ForeignKey.CASCADE))])
public class Pet(@PrimaryKey(autoGenerate = true),
var name: String,
var userId: Long?,
@Ignore var user: User?)
Normally we would query all pets like this:
@Dao
interface PetsDao {
@Query("SELECT * FROM pets")
fun getAll(): Flowable<List<Pet>>
}
But how can we make it so that the User is attached to the Pet object automatically? Like the query would be:
@Dao
interface PetsDao {
@Query("SELECT * FROM pets p JOIN users u ON u.id = p.userId")
fun getAllWithUser(): Flowable<List<Pet>>
}
And then we could use pet.user.name without having to query the user separately.
您应该使用@Embedded
(资源: https : //developer.android.com/reference/android/arch/persistence/room/Relation.html )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.