I followed the android dev guide to define Room many-to-many relationship: https://developer.android.com/training/data-storage/room/relationships#many-to-many
data class Playlist(
@PrimaryKey val playlistId: Long,
val playlistName: String
)
@Entity
data class Song(
@PrimaryKey val songId: Long,
val songName: String,
val artist: String
)
@Entity(primaryKeys = ["playlistId", "songId"])
data class PlaylistSongCrossRef(
val playlistId: Long,
val songId: Long
)
data class PlaylistWithSongs(
@Embedded val playlist: Playlist,
@Relation(
parentColumn = "playlistId",
entityColumn = "songId",
associateBy = @Junction(PlaylistSongCrossRef::class)
)
val songs: List<Song>
)
// Dao
@Transaction
@Query("SELECT * FROM Playlist")
fun getPlaylistsWithSongs(): List<PlaylistWithSongs>
The above works fine. However, I also want to save the sound property (i.e. Base volume...) of a song according to which playlist it belongs. For the same song, the volume is high when it is in "party" playlist and low when it is in "cool down" playlist. Similar for the same playlist, the volume is high for some songs and low for the rest.
So I changed the above PlaylistSongCrossRef and added the Dao as the following:
@Entity(table="playlistSongCrossRef", primaryKeys = ["playlistId", "songId"])
data class PlaylistSongCrossRef(
val playlistId: Long,
val songId: Long,
val baseVolume: Double
)
data class PlaylistWithSongs(
@Embedded val playlist: Playlist,
@Relation(
parentColumn = "playlistId",
entityColumn = "songId",
associateBy = Junction(PlaylistSongCrossRef::class)
)
val songs: List<Song>
@Relation(
parentColumn = "playlistId",
entityColumn = "baseVolume",
associateBy = Junction(PlaylistSongCrossRef::class)
)
val baseVolumes: List<PlaylistSongCrossRef>
)
// Dao
@Query("SELECT * FROM Playlist WHERE playlistId = :playlistId ")
fun getPlaylistsWithSongs(playlistId: Int): List<PlaylistWithSongs>
However, the dao query does not work as expected. When the same baseVolume is stored in different song-playlistCrossRef pairs, the query will return duplicated entries.
I am not sure if this is the wrong query in dao or I need to re-design the Room DB structure. Thank you so much in advance!