I have two entities in my room database in an Android application. The concept is that every Site has many Groups.
@Entity(tableName = "sites")
data class Site(
@ColumnInfo(name = "server_id")
var serverId: Long,
@PrimaryKey
@ColumnInfo(name = "site_id")
val siteId: Int,
@ColumnInfo(name = "description", defaultValue = "")
val description: String
)
@Entity(tableName = "groups")
data class Group(
@ColumnInfo(name = "server_id")
val serverId: Long,
@PrimaryKey
@ColumnInfo(name = "group_id")
var groupId: Int,
@ColumnInfo(name = "site_id")
val siteId: Int,
@ColumnInfo(name = "description", defaultValue = "")
val description: String
)
So i want given a siteId and a groupId, two fetch from the Database a POJO called SiteWithGroup which is
data class SiteWithGroup(
@Embedded
val site: Site,
@Relation(parentColumn = "site_id", entityColumn = "site_id", entity = Group::class)
val group: Group
)
I created a MediatorLiveData which observes the siteId, groupId and when it has both it returns a query from db
private val siteGroupPair = MediatorLiveData<Pair<Int?, Int?>>().apply {
addSource(siteId) {
value = Pair(it, groupId.value)
}
addSource(groupId) {
value = Pair(siteId.value, it)
}
}
override val siteGroup: LiveData<SiteWithGroup>
get() = Transformations.switchMap(siteGroupPair) {
it?.let { pair ->
if (pair.first != null && pair.second != null)
sitesRepository.siteWithGroup(pair.first!!, pair.second!!)
else null
}
}
//Dao query
@Query("""Select * from groups
inner join sites on groups.site_id = :siteId
where sites.site_id = :siteId and groups.group_id = :groupId
""")
fun getByIdWithGroups(siteId: Int, groupId: Int): LiveData<SiteWithGroup>
If we suppose that the siteId, groupId = 1, 1 and i have the following entries in my db
Group entity
serverId, groupId, siteId, description
1 1 1 "Group1 description"
1 2 1 "Group2 description"
________________________________________________
Site entity
serverId, siteId, description
1 1 "Site1 description"
we expect from out result to be
SiteWithGroup(
site=Site(serverId=1, siteId=1, description=Site1 description),
group=Group(serverId=1, groupId=2, siteId=1, description=Group2 description)
)
but instead we get this
SiteWithGroup(
site=Site(serverId=1, siteId=1, description= !!!<<Group1 description>>!!!),
group=Group(serverId=1, groupId=<<2>>, siteId=1, description= <<Group2 description>>)
)
The site entity get the groups description and the wrong one!! Seems like the group contraint is not applied at all.How is this happening?? How can i fix it?? Thank you
However on my UI the result is