Android Room embedded relationship query results - android

I am currently trying to get results from a query of nested relationships in Room. Here Are my classes/database entities involved:
#Entity
data class PrayerRequestEntity(
var title: String,
var details: String,
var category: String,
var isAnswered: Boolean,
var prayerCount: Int,
var dateCreated: Date,
var dateUpdated: Date
) {
#PrimaryKey(autoGenerate = true)
var prayerRequestId: Int = 0
}
#Entity
data class PrayerPlanEntity(
var title: String,
var sessionCount: Int,
var dateCreated: Date,
var dateUpdated: Date
) {
#PrimaryKey(autoGenerate = true)
var planId: Int = 0
}
#Entity(primaryKeys = ["planId", "prayerRequestId"])
data class PrayerPlanPrayerRequestJoinEntity(
val planId: Int,
val prayerRequestId: Int
)
I am trying to get a list of PrayerPlanEtities along with the PrayerRequestEntities associated with each and have no problem using the following return:
data class PrayerPlanPrayerRequestsJoin(
#Embedded
val prayerPlan: PrayerPlanEntity,
#Relation(
parentColumn = "planId",
entityColumn = "prayerRequestId",
associateBy = Junction(PrayerPlanPrayerRequestJoinEntity::class)
)
val prayers: List<PrayerPlanEntity>
)
I need to also query the relationships of PrayerRequestEntity in that same query so Imodify the aforementioned class like so:
data class PrayerPlanPrayerRequestsJoin(
#Embedded
val prayerPlan: PrayerPlanEntity,
#Relation(
parentColumn = "planId",
entityColumn = "prayerRequestId",
associateBy = Junction(PrayerPlanPrayerRequestJoinEntity::class)
)
val prayers: List<PrayerRequestJoin>
)
PrayerRequestJoin is a previous relationship I created which works perfectly fine on it own and looks like so:
data class PrayerRequestJoin(
#Embedded
val prayerRequest: PrayerRequestEntity,
#Relation(
parentColumn = "prayerRequestId",
entityColumn = "prayerRequestCategoryId",
associateBy = Junction(PrayerRequestCategoryJoinEntity::class)
)
val category: PrayerRequestCategoryEntity,
#Relation(
parentColumn = "prayerRequestId",
entityColumn = "photoId",
associateBy = Junction(PrayerRequestPhotoJoinEntity::class)
)
val photos: List<PhotoEntity>,
#Relation(
parentColumn = "prayerRequestId",
entityColumn = "noteId",
associateBy = Junction(PrayerRequestNoteJoinEntity::class)
)
val notes: List<NoteEntity>
)
But now I am getting two build errors an Android Studio:
error: constructor PrayerPlanPrayerRequestsJoin in class PrayerPlanPrayerRequestsJoin cannot be applied to given types;
_item = new PrayerPlanPrayerRequestsJoin();
^
required: PrayerPlanEntity,List
found: no arguments
reason: actual and formal argument lists differ in length
and also:
error: prayerPlan has private access in PrayerPlanPrayerRequestsJoin
_item.prayerPlan = _tmpPrayerPlan;
Can anyone provide some insight on what may be causing this issue?

I believe that your issue is with the #Query's rather than with the relationships.
Upon closer inspection the messages shows java code e.g. termination with ;'s.
Therefore the issue is within the generated java and it would appear (from creating a working example) that the issue is in the code underlying the class or classes annotated with #Dao
i.e. _item does not appear in the java for the class annotated with #Database. Whilst _item = new .... appears for each #Query annotated function. e.g.
for a Query using SELECT * FROM PrayerPlanPrayerRequestJoinEntity then the code includes _item = new PrayerPlanPrayerRequestJoinEntity(_tmpPlanId,_tmpPrayerRequestId);
for a Query using "SELECT * FROM prayerRequestEntity" then the code includes _item = new PrayerRequestJoin(_tmpPrayerRequest,_tmpCategory_1,_tmpPhotosCollection_1,_tmpNotesCollection_1);
As can be seen these are used to build the final result. The first example being the closest from the working example but there is no issue.
As such I believe that the issue is not with the relationships (working example runs OK) but the issue is with the #Query annotated functions.
I would suggest commenting them all out and adding each until you find the culprit.
The working example
Note that this example introduces/uses some shortcuts so the code differs a little.
the code is run on the main thread so uses .allowMainThreadQueries
Long's are used instead of Ints for id's (they should really always be longs as they can be signed 64 bit)
Autogenerate has not been used for classes that have been guessed such as NoteEntity (autogenerate (which equates to AUTOINCREMENT) is actually not recommended by SQLite themselves The AUTOINCREMENT keyword imposes extra CPU, memory, disk space, and disk I/O overhead and should be avoided if not strictly needed. It is usually not needed. https://sqlite.org/autoinc.html)
TypeConverters have been avoided
The code:-
NoteEntity made up just to test, so very simple
#Entity
data class NoteEntity(
#PrimaryKey
var noteId: Long? = null,
var noteText: String = ""
)
PhotoEntity made up ....
#Entity
data class PhotoEntity(
#PrimaryKey
var photoId: Long? = null,
var photoImage: String = "unknown"
)
PrayerPlanEntity
#Entity
data class PrayerPlanEntity(
var title: String,
var sessionCount: Int,
var dateCreated: String, /* changed for brevity */
var dateUpdated: String /* changed for brevity */
) {
#PrimaryKey(autoGenerate = true)
var planId: Long = 0
}
PrayerPlanPrayerRequestJoinEntity
#Entity(primaryKeys = ["planId", "prayerRequestId"])
data class PrayerPlanPrayerRequestJoinEntity(
val planId: Long,
val prayerRequestId: Long
)
PrayerPlanPrayerRequestsJoin assume the 2nd is as it is now
data class PrayerPlanPrayerRequestsJoin(
/*
#Embedded
val prayerPlan: PrayerPlanEntity,
#Relation(
parentColumn = "planId",
entityColumn = "prayerRequestId",
associateBy = Junction(PrayerPlanPrayerRequestJoinEntity::class)
)
val prayers: List<PrayerPlanEntity>
*/
#Embedded
val prayerPlan: PrayerPlanEntity,
#Relation(
parentColumn = "planId",
entityColumn = "prayerRequestId",
associateBy = Junction(PrayerPlanPrayerRequestJoinEntity::class)
)
val prayers: List<PrayerRequestJoin>
)
PrayerRequestCategoryEntity made up ....
#Entity
data class PrayerRequestCategoryEntity(
#PrimaryKey
var prayerRequestCategoryId: Long? = null,
var categoryName: String
)
PrayerRequestCategoryJoinEntity made up ....
#Entity(primaryKeys = ["prayerRequestId", "prayerRequestCategoryId"])
data class PrayerRequestCategoryJoinEntity(
val prayerRequestId: Long,
val prayerRequestCategoryId: Long
)
PrayerRequestEntity
#Entity
data class PrayerRequestEntity(
var title: String,
var details: String,
var category: String,
var isAnswered: Boolean,
var prayerCount: Int,
var dateCreated: String, /* changed for brevity */
var dateUpdated: String /* changed for brevity */
) {
#PrimaryKey(autoGenerate = true)
var prayerRequestId: Long = 0
}
PrayerRequestJoin
data class PrayerRequestJoin(
#Embedded
val prayerRequest: PrayerRequestEntity,
#Relation(
parentColumn = "prayerRequestId",
entityColumn = "prayerRequestCategoryId",
associateBy = Junction(PrayerRequestCategoryJoinEntity::class)
)
val category: PrayerRequestCategoryEntity,
#Relation(
parentColumn = "prayerRequestId",
entityColumn = "photoId",
associateBy = Junction(PrayerRequestPhotoJoinEntity::class)
)
val photos: List<PhotoEntity>,
#Relation(
parentColumn = "prayerRequestId",
entityColumn = "noteId",
associateBy = Junction(PrayerRequestNoteJoinEntity::class)
)
val notes: List<NoteEntity>
)
PrayerRequestNoteJoinEntity made up
#Entity(primaryKeys = ["prayerRequestId", "noteId"])
data class PrayerRequestNoteJoinEntity(
val prayerRequestId: Long,
val noteId: Long
)
PrayerRequestPhotoJoinEntity made up ....
#Entity(primaryKeys = ["prayerRequestId", "photoId"])
data class PrayerRequestPhotoJoinEntity(
val prayerRequestId: Long,
val photoId: Long
)
AllDAO made up
#Dao
abstract class AllDAO {
#Insert(onConflict = OnConflictStrategy.IGNORE)
abstract fun insert(photoEntity: PhotoEntity): Long
#Insert(onConflict = OnConflictStrategy.IGNORE)
abstract fun insert(noteEntity: NoteEntity): Long
#Insert(onConflict = OnConflictStrategy.IGNORE)
abstract fun insert(prayerPlanEntity: PrayerPlanEntity): Long
#Insert(onConflict = OnConflictStrategy.IGNORE)
abstract fun insert(prayerRequestCategoryEntity: PrayerRequestCategoryEntity): Long
#Insert(onConflict = OnConflictStrategy.IGNORE)
abstract fun insert(prayerRequestEntity: PrayerRequestEntity): Long
#Insert(onConflict = OnConflictStrategy.IGNORE)
abstract fun insert(prayerPlanPrayerRequestJoinEntity: PrayerPlanPrayerRequestJoinEntity): Long
#Insert(onConflict = OnConflictStrategy.IGNORE)
abstract fun insert(prayerRequestCategoryJoinEntity: PrayerRequestCategoryJoinEntity): Long
#Insert(onConflict = OnConflictStrategy.IGNORE)
abstract fun insert(prayerRequestNoteJoinEntity: PrayerRequestNoteJoinEntity): Long
#Insert(onConflict = OnConflictStrategy.IGNORE)
abstract fun insert(prayerRequestPhotoJoinEntity: PrayerRequestPhotoJoinEntity): Long
#Query("SELECT * FROM prayerRequestEntity")
abstract fun getAllPrayerRequests(): List<PrayerRequestEntity>
#Query("SELECT * FROM prayerPlanEntity")
abstract fun getAllPrayerPlans(): List<PrayerPlanEntity>
#Query("SELECT * FROM PrayerPlanPrayerRequestJoinEntity")
abstract fun getAllPrayerPlanRequestJoins(): List<PrayerPlanPrayerRequestJoinEntity>
#Query("SELECT * FROM prayerRequestEntity")
abstract fun getAllPrayerRequestsWithCategoryNotesAndPhotos(): List<PrayerRequestJoin>
}
TheDatabase made up
#Database(entities = [
PhotoEntity::class,
NoteEntity::class,
PrayerRequestEntity::class,
PrayerPlanEntity::class,
PrayerRequestCategoryEntity::class,
PrayerRequestCategoryJoinEntity::class,
PrayerRequestNoteJoinEntity::class,
PrayerRequestPhotoJoinEntity::class,
PrayerPlanPrayerRequestJoinEntity::class]
, version = 1,
exportSchema = false
)
abstract class TheDatabase: RoomDatabase() {
abstract fun getAllDAO(): AllDAO
companion object {
private var instance: TheDatabase? = null
fun getInstance(context: Context): TheDatabase {
if (instance == null) {
instance = Room.databaseBuilder(context,TheDatabase::class.java,"prayer.db")
.allowMainThreadQueries()
.build()
}
return instance as TheDatabase
}
}
}
Last but not least an activity to do a simple test of the related data via the getAllPrayerRequestsWithCategoryNotesAndPhotos query:-
class MainActivity : AppCompatActivity() {
lateinit var db: TheDatabase
lateinit var dao: AllDAO
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
db = TheDatabase.getInstance(this)
dao = db.getAllDAO()
val n1id = dao.insert(NoteEntity(noteText = "Note1"))
val n2id = dao.insert(NoteEntity(noteText = "Note2"))
val n3id = dao.insert(NoteEntity(noteText = "Note3"))
val photo1id = dao.insert(PhotoEntity(photoImage = "photo1"))
val photo2id = dao.insert(PhotoEntity(photoImage = "photo2"))
val photo3id = dao.insert(PhotoEntity(photoImage = "photo3"))
val pp1id = dao.insert(PrayerPlanEntity(title = "PP01",10,"today","never"))
val pcat01id = dao.insert(PrayerRequestCategoryEntity(categoryName = "CAT01"))
val pcat02id = dao.insert(PrayerRequestCategoryEntity(categoryName = "CAT02"))
val pcat03id = dao.insert(PrayerRequestCategoryEntity(categoryName = "CAT03"))
val pr01id =dao.insert(PrayerRequestEntity("PR01","details01","cat01",false,10,"today","never"))
dao.insert(prayerPlanPrayerRequestJoinEntity = PrayerPlanPrayerRequestJoinEntity(prayerRequestId = pr01id, planId = pp1id))
dao.insert(PrayerRequestPhotoJoinEntity(pr01id,photo1id))
dao.insert(PrayerRequestPhotoJoinEntity(pr01id,photo2id))
dao.insert(PrayerRequestPhotoJoinEntity(pr01id,photo3id))
dao.insert(PrayerRequestCategoryJoinEntity(pr01id,n1id))
dao.insert(PrayerRequestNoteJoinEntity(pr01id,n2id))
dao.insert(PrayerRequestNoteJoinEntity(pr01id,n3id))
dao.insert(PrayerRequestCategoryJoinEntity(pr01id,pcat01id))
/* Extract the Data and output to the log */
for (prj: PrayerRequestJoin in dao.getAllPrayerRequestsWithCategoryNotesAndPhotos()) {
Log.d("DBINFO","Prayer Request = ${prj.prayerRequest.details} \n\tRequestCategory = ${prj.category.categoryName} ID is ${prj.category.prayerRequestCategoryId}")
for (photos: PhotoEntity in prj.photos) {
Log.d("DBINFO","\tPhoto = ${photos.photoImage} ID = ${photos.photoId}")
}
for (notes: NoteEntity in prj.notes) {
Log.d("DBINFO","\tNote = ${notes.noteText} ID = ${notes.noteId}")
}
}
}
}
Finally the result from the Log:-
2022-03-24 12:52:35.758 D/DBINFO: Prayer Request = details01
RequestCategory = CAT01 ID is 1
2022-03-24 12:52:35.758 D/DBINFO: Photo = photo1 ID = 1
2022-03-24 12:52:35.758 D/DBINFO: Photo = photo2 ID = 2
2022-03-24 12:52:35.758 D/DBINFO: Photo = photo3 ID = 3
2022-03-24 12:52:35.758 D/DBINFO: Note = Note2 ID = 2
2022-03-24 12:52:35.759 D/DBINFO: Note = Note3 ID = 3

Related

Android Room Many to many relation with associateBy and Junction not compiling

I tried same code as of given in https://developer.android.com/training/data-storage/room/relationships#many-to-many exactly with room 2.2.0.
#Entity
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, parentColumn = "playlistId", entityColumn = "songId")
)
val songs: List<Song>
)
I have more complex data but when i tried same code from link it shows
error: Not sure how to convert a Cursor to this method's return type (java.util.List<com.skybase.compose_tut.PlaylistWithSongs>).
I am wondering why this sample code not working?
You issue will be with one of the functions (methods in java) in the #Dao annotated interface (or abstract class). The code provided (Song, Playlist, PlaylistSongCrossref and the POJO PLaylistsWithSongs) are all OK.
In the #Dao annotated interface you want something like:-
#Query("SELECT * FROM playlist")
fun getAllPlayListsWithSongs(): List<PlaylistWithSongs>
The return type being List<PlaylistWithSongs>
Demo
With a project with your code and the following extra code for the database:-
#Database(entities = [Song::class,Playlist::class,PlaylistSongCrossRef::class], exportSchema = false, version = 1)
abstract class TheDatabase: RoomDatabase() {
abstract fun getAllDAOs(): AllDAOs
companion object {
private var instance: TheDatabase?=null
fun getInstance(context: Context): TheDatabase {
if (instance==null) {
instance = Room.databaseBuilder(context,TheDatabase::class.java,"the_database")
.allowMainThreadQueries() /* for convenience/brevity of demo */
.build()
}
return instance as TheDatabase
}
}
}
#Dao
interface AllDAOs {
#Insert(onConflict = OnConflictStrategy.IGNORE)
fun insert(song: Song): Long
#Insert(onConflict = OnConflictStrategy.IGNORE)
fun insert(playlist: Playlist): Long
#Insert(onConflict = OnConflictStrategy.IGNORE)
fun insert(playlistSongCrossRef: PlaylistSongCrossRef): Long
#Query("SELECT * FROM playlist")
fun getAllPlayListsWithSongs(): List<PlaylistWithSongs>
}
and then the following activity code:-
class MainActivity : AppCompatActivity() {
lateinit var dbInstance: TheDatabase
lateinit var dao: AllDAOs
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
dbInstance = TheDatabase.getInstance(this)
dao = dbInstance.getAllDAOs()
var song1Id = dao.insert(Song(songId=1, songName = "Song1", artist = "Artist1"))
var song2Id = dao.insert(Song(songId=2, songName = "Song2", artist = "Artist1"))
var song3Id = dao.insert(Song(songId=3, songName = "Song3", artist = "Artist2"))
var pl1id = dao.insert(Playlist(playlistId = 100, playlistName = "Playlist 1"))
var pl2id = dao.insert(Playlist(playlistId = 101, playlistName = "Playlist 2"))
var pl3id = dao.insert(Playlist(playlistId = 102, playlistName = "Playlist 3"))
dao.insert(PlaylistSongCrossRef(pl1id,song1Id))
dao.insert(PlaylistSongCrossRef(pl1id,song2Id))
dao.insert(PlaylistSongCrossRef(pl1id,song3Id))
dao.insert(PlaylistSongCrossRef(pl2id,song2Id))
val sb = StringBuilder()
for (pws in dao.getAllPlayListsWithSongs()) {
sb.clear()
for (s in pws.songs) {
sb.append("\n\tSong ID is ${s.songId} Name is ${s.songName} Artist is ${s.artist}")
}
Log.d("DBINFO","PLaylist ID is ${pws.playlist.playlistId} Name is ${pws.playlist.playlistName} it has ${pws.songs.size} songs: They are:-${sb}")
}
}
}
Then it compiles (using Room 2.2.0 libraries) fine and when run results in the expected:-
D/DBINFO: PLaylist ID is 100 Name is Playlist 1 it has 3 songs: They are:-
Song ID is 1 Name is Song1 Artist is Artist1
Song ID is 2 Name is Song2 Artist is Artist1
Song ID is 3 Name is Song3 Artist is Artist2
D/DBINFO: PLaylist ID is 101 Name is Playlist 2 it has 1 songs: They are:-
Song ID is 2 Name is Song2 Artist is Artist1
D/DBINFO: PLaylist ID is 102 Name is Playlist 3 it has 0 songs: They are:-

ROOM database entity modeling

There must be a better way of doing this. I want to create a database table with all my clothing and have subcategories of clothing, like outerwear, dresses, shoes, etc. They all will have the same attributes (Id, name, image, about, price). Couldn't I create one table? I believe this is a One-to-Many relationship.
#Serializable
#Entity(tableName = CLOTHING_DATABASE_TABLE)
data class Clothing(
#PrimaryKey(autoGenerate = false)
val id: Int,
val name: String,
val image: String,
val about: String,
val price: String
)
#Serializable
#Entity(tableName = POPULAR_DATABASE_TABLE)
data class Popular(
#PrimaryKey(autoGenerate = false)
val popularId: Int,
val name: String,
val image: String,
val about: String,
val price: String
)
#Serializable
#Entity(tableName = OUTERWEAR_DATABASE_TABLE)
data class Outerwear(
#PrimaryKey(autoGenerate = false)
val outerwearId: Int,
val name: String,
val image: String,
val about: String,
val price: String
)
#Serializable
#Entity(tableName = TOPS_DATABASE_TABLE)
data class Tops(
#PrimaryKey(autoGenerate = false)
val topsId: Int,
val name: String,
val image: String,
val about: String,
val price: String
)
#Serializable
#Entity(tableName = SWIMWEAR_DATABASE_TABLE)
data class Swimwear(
#PrimaryKey(autoGenerate = false)
val swimwearId: Int,
val name: String,
val image: String,
val about: String,
val price: String
)
#Serializable
#Entity(tableName = SHOES_DATABASE_TABLE)
data class Shoes(
#PrimaryKey(autoGenerate = false)
val shoesId: Int,
val name: String,
val image: String,
val about: String,
val price: String
)
#Serializable
#Entity(tableName = BUNDLES_DATABASE_TABLE)
data class Bundles(
#PrimaryKey(autoGenerate = false)
val bundlesId: Int,
val name: String,
val image: String,
val about: String,
val price: String
)
#Serializable
#Entity(tableName = DRESSES_DATABASE_TABLE)
data class Dresses(
#PrimaryKey(autoGenerate = false)
val dressesId: Int,
val name: String,
val image: String,
val about: String,
val price: String
)
#Serializable
#Entity(tableName = PAJAMAS_DATABASE_TABLE)
data class Pajamas(
#PrimaryKey(autoGenerate = false)
val pajamasId: Int,
val name: String,
val image: String,
val about: String,
val price: String
)
#Serializable
#Entity(tableName = ACCESSORIES_DATABASE_TABLE)
data class Accessories(
#PrimaryKey(autoGenerate = false)
val accessoriesId: Int,
val name: String,
val image: String,
val about: String,
val price: String
)
You would typically have either 2 or 3 tables (3 for a many-many i.e. an item of clothing could have multiple sub-categories).
For one-many have a clothing table which has a column for the sub-category that references(relates) to the single sub-category and a sub-category table that is referenced according to a unique column (the primary key).
For the many-many you have the clothing table (without the column to reference the single sub-category), the sub-category table and then a third table that has two columns, one for the reference to the clothing and the other for the reference to the sub-category with the primary key being a composite of both.
So you could have:-
#Entity(tableName = CLOTHING_DATABASE_TABLE)
data class Clothing(
#PrimaryKey(autoGenerate = false)
val id: Long, /* should really be Long as */
val subCategoryReference: Long, /*<<<<< ADDED for the 1 subcategory */
val name: String,
val image: String,
val about: String,
val price: String
)
and :-
#Entity(tableName = SUBCATEGORY_DATABASE_TABLE)
data class SubCategory(
#PrimaryKey
val id: Long?,
val subCategoryName: String
)
to enforce referential integrity you could add a foreign key constraint to the subCategoryReference column of the clothing table.
If you wanted a many-many, allowing a clothing to have multiple sub-categories then you could have the third table as :-
#Entity(
tableName = CLOTHING_SUBCATEGORY_MAP_DATABASE_TABLE,
primaryKeys = ["clothingMap","subcategoryMap"],
)
data class ClothingSubCategoryMap(
val clothingMap: Long,
#ColumnInfo(index = true)
val subcategoryMap: Long
)
Of course you could have a single clothing table and just have a column for the sub-category. However this would be considered as not being normalised as you would be duplicating the sub-category throughout.
Example 1-many (i.e. using the 2 tables Clothing and SubCategory)
As you would very likely want to retrieve clothing along with it's sub-category then you would have a POJO that uses the #Embedded and #Relation annotations e.g.
data class ClothingWithSingleSubCategory (
#Embedded
val clothing: Clothing,
#Relation(
entity = SubCategory::class,
parentColumn = "subCategoryReference",
entityColumn = "id"
)
val subCategory: SubCategory
)
You could then have the following as an #Dao annotated class :-
#Dao
interface AllDao {
#Insert(onConflict = IGNORE)
fun insert(clothing: Clothing): Long
#Insert(onConflict = IGNORE)
fun insert(subCategory: SubCategory): Long
#Transaction
#Query("SELECT * FROM clothing")
fun getAllClothingWithSubCategory(): List<ClothingWithSingleSubCategory>
}
With a suitable #Database annotated class you could then have something like the following in an activity:-
class MainActivity : AppCompatActivity() {
lateinit var db: TheDatabase
lateinit var dao: AllDao
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
db = TheDatabase.getInstance(this)
dao = db.getAllDao()
val sc_popular = dao.insert(SubCategory(null,"Popular"))
val sc_outerwear = dao.insert(SubCategory(null,"OuterWear"))
val sc_tops = dao.insert(SubCategory(null,"Tops"))
val sc_swimwear = dao.insert(SubCategory(100,"Swimwear"))
val sc_shoes = dao.insert(SubCategory(null,"Shoes"))
val sc_dresses = dao.insert(SubCategory(null,"Dresses"))
val sc_pyjamas = dao.insert(SubCategory(null,"Pyjamas"))
dao.insert(Clothing(100200300400,sc_popular,"Jeans","jeans_image","blah","100.55"))
dao.insert(Clothing(100200300500,sc_outerwear,"Anorak","anorak_image","blah","214.55"))
for (cwsc: ClothingWithSingleSubCategory in dao.getAllClothingWithSubCategory()) {
Log.d("DBINFO","Name = ${cwsc.clothing.name} Price is ${cwsc.clothing.price} Sub-Category is ${cwsc.subCategory.subCategoryName}")
}
}
}
When run the log would then include:-
D/DBINFO: Name = Jeans Price is 100.55 Sub-Category is Popular
D/DBINFO: Name = Anorak Price is 214.55 Sub-Category is OuterWear
Example many-many
Like the 1-many you will want a POJO BUT one that has a List of sub-categories obtained via the mapping table. This uses the #Embeded annotation and the #Relation annotation but extended to include the associateBy to inform Room about the intermediate table. So you could have:-
data class ClothingWithListOfSubCategories(
#Embedded
val clothing: Clothing,
#Relation(
entity = SubCategory::class,
parentColumn = "id",
entityColumn = "id",
associateBy = Junction(
value = ClothingSubCategoryMap::class,
parentColumn = "clothingMap",
entityColumn = "subcategoryMap"
)
)
val subCategories: List<SubCategory>
)
The you could have the following in an #Dao annotated class:-
/* ADDED for many-many */
#Insert(onConflict = IGNORE)
fun insert(clothingSubCategoryMap: ClothingSubCategoryMap): Long
#Transaction
#Query("SELECT * FROM clothing")
fun getAllClothingWithSubCategories(): List<ClothingWithListOfSubCategories>
and if the activity were extended to include :-
/* Added for many-many */
/* Note utilises clothing and sub-categories above */
dao.insert(ClothingSubCategoryMap(jeans,sc_popular))
dao.insert(ClothingSubCategoryMap(jeans,sc_swimwear))
dao.insert(ClothingSubCategoryMap(jeans,sc_shoes))
dao.insert(ClothingSubCategoryMap(anorak,sc_popular))
dao.insert(ClothingSubCategoryMap(anorak,sc_outerwear))
for(cwlsc: ClothingWithListOfSubCategories in dao.getAllClothingWithSubCategories()) {
Log.d("DBINFO","Name = ${cwlsc.clothing.name} Price is ${cwlsc.clothing.price} it is in ${cwlsc.subCategories.size} sub-categories. They are:-")
for(sc: SubCategory in cwlsc.subCategories) {
Log.d("DBINFO","\t${sc.subCategoryName}")
}
}
The the log would also include :-
D/DBINFO: Name = Jeans Price is 100.55 it is in 3 sub-categories. They are:-
D/DBINFO: Popular
D/DBINFO: Swimwear
D/DBINFO: Shoes
D/DBINFO: Name = Anorak Price is 214.55 it is in 2 sub-categories. They are:-
D/DBINFO: Popular
D/DBINFO: OuterWear

Room one-to-many, to many

I am little a bit confused on how i should set up a data class consisting of two lists.
I have a data class looking like this
#Entity(tableName = "recipe")
data class Recipe(
#PrimaryKey(autoGenerate = false)
val recipeName: String,
//val keyIngrediens: List<KeyIngredient>,
//val steps: List<steps>
So for KeyIngrediens i have set it up like this and it works perfectly without problems
#Entity
data class KeyIngredients(
#PrimaryKey(autoGenerate = false)
val title: String,
val image: String,
val undertitle: Int,
val recipeName: String
)
data class RecipeWithkeyIngredients(
#Embedded val recipe: Recipe,
#Relation(
parentColumn = "recipeName",
entityColumn = "recipeName"
)
val keyIngredients: List<KeyIngredients>
)
So basically, i got it to work with one list and one object, but Im a bit confused as how i should handle it when i have two lists in a single object. Right now I'm calling RecipeWithKeyIngredients which returns the recipe object with the list of key ingredients, but i don't know how to make it also contain the steps list.
In short it should be like RecipeWithkeyIngredientsANDsteps if that is possible.
This is not enough for recipes. A recipe contains many ingredients, an ingredient belongs to many recipes. So it should be handled with many-to-many relationship.
#Entity
data class Recipe(
#PrimaryKey
val recipeId: Long,
val name: String
)
#Entity
data class KeyIngredient(
#PrimaryKey
val keyIngredientId: Long,
val title: String,
val image: String,
val undertitle: Int,
)
#Entity
data class Step(
#PrimaryKey
val stepId: Long,
val instruction: String,
val stepRecipeId: Long
)
#Entity(
primaryKeys = ["recipeId", "keyIngredientId"]
)
data class RecipeKeyIngredient(
val recipeId: Long,
val keyIngredientId: Long
)
Get the list of ingredients of a recipe
data class RecipeWithIngredients (
#Embedded
val recipe: Recipe,
#Relation(
parentColumn = "recipeId",
entity = KeyIngredient::class,
entityColumn = "ingredientId",
associateBy = Junction(
value = RecipeKeyIngredient::class,
parentColumn = "recipeId",
entityColumn = "keyIngredientId"
)
)
val keyIngredients: List<KeyIngredient>
)
Get the list of recipes with the same ingredient
data class IngredientWithRecipes(
#Embedded
val ingredient: Ingredient,
#Relation(
parentColumn = "ingredientId",
entity = Recipe::class,
entityColumn = "recipeId",
associateBy = Junction(
value = RecipeKeyIngredient::class,
parentColumn = "ingredientId",
entityColumn = "recipeId"
)
)
val recipes: List<Recipe>
)
Now you can query database for the result as:
#Dao
interface RecipeKeyIngredientDao {
#Query("SELECT * FROM Recipe")
fun getRecipeWithIngredients(): LiveData<List<RecipeWithIngredients>>
#Query("SELECT * FROM KeyIngredient")
fun getIngredientWithRecipes(): LiveData<List<IngredientWithRecipes>>
}
For the other part of the question, a recipe typically contains specific set of steps (instructions?) and to define the relationship between recipe and steps you will need nested relationship which defines one-to-many relationship between recipe and steps, and get the recipe from already modelled IngredientsOfRecipe instead of Recipe table which will give recipe with ingredients. Model the same as
data class RecipeWithIngredientsAndSteps(
#Embedded val recipe: IngredientsOfRecipe
#Relation(
entity = Step::class,
parentColumn = "recipeId",
entityColumn = "stepRecipeId"
)
val steps: List<Step>
)
Query using single transaction as follows
#Transaction
#Query("SELECT * FROM Recipe")
fun getRecipeWithIngredientsAndSteps(): List<RecipeWithIngredientsAndSteps>
Please refer to this
Assuming your Steps data class as follows:
#Entity
data class Steps(
#PrimaryKay
val stepName: String,
val duration: Int,
val recipeName: String,
val rank: Int
)
data class RecipeWithKeyIngredientsAndSteps(
#Embedded recipe: Recipe,
#Relation(
parentColumn = "recipeName",
entityColumn = "recipeName"
)
val keyIngredients: List<KeyIngredients>,
#Relation(
parentColumn = "recipeName",
entityColumn = "recipeName"
)
val steps: List<Steps>
)
At the end it's still a One-to-N Relationship

Android Room Relation returns an invalid list

I have a query with a complex relation.
data class GameWithHouseworkResult(
#Embedded val game:GameClass,
#Relation(
entity = GameHouseworkResult::class,
parentColumn = "gameId",
entityColumn = "houseworkId" ,
associateBy = Junction(value=GameHouseworkResult::class)
)
val houseworkAndResult: List<HouseworkAndResult>
)
I have 3 entities and one additional class
#Entity
class GameClass(
#PrimaryKey(autoGenerate = true)
var gameId: Int = 0,
val mainPlayer:String,
var secondPlayer:String=""
}
#Entity
data class HouseworkClass(
#PrimaryKey
val houseworkId: Int,
val name:String,
val score:Int
) {
}
#Entity(primaryKeys = ["gameId", "houseworkId"])
class GameHouseworkResult(
var gameId: Long,
val houseworkId:Long,
val userToken:String,
val isDone:Boolean?= null) {
}
data class HouseworkAndResult(
#Embedded val gameHouseworkResult:GameHouseworkResult,
#Relation(
parentColumn = "houseworkId",
entityColumn = "houseworkId"
)
val housework: HouseworkClass
)
GameHouseworkResult is a binder class, it contains the following data
#Transaction
#Query("SELECT * FROM GameClass where gameId=:id")
suspend fun getGameWithHouseworkResult(id:Long): GameWithHouseworkResult
when I send a request with gameId = 26, I should get a list(houseworkAndResult) with five elements, but I get a list of 10 elements, and each one says that gameId = 26.
Most likely this is due to the same houseworkId, but I cannot understand where I went wrong when drawing up the relations. Please HELP me!
Don't worry, I've found a solution. I confused the #relation and used many-to-many instead of one-to-many. Correct code
data class GameWithHouseworkResult(
#Embedded val game:GameClass,
#Relation(
entity = GameHouseworkResult::class,
parentColumn = "gameId",
entityColumn = "gameId"
)
val houseworkAndResult: List<HouseworkAndResult>
)

Android Room - Many-to-many relationship not returning relation entities

I've followed the documentation provided on android developer guides and a Medium article.
I'm trying to return a playlist of songs, but want a list of entities and not just the IDs. Following the above links I have this.
My Entities:
#Entity
data class MediaEntity(
#PrimaryKey val identifier: String,
val imageUrl: String,
val title: String,
val description: String,
val media: String,
val duration: Double,
val progress: Int,
val listenedToCompletion: Boolean
)
#Entity
data class PlaylistEntity(
#PrimaryKey val playlistId: String,
val playlistName: String,
val playlistDescription: String = "",
val currentPosition: Int = 0
)
#Entity(primaryKeys = ["playlistId", "identifier"])
data class PlaylistMediaLinkEntity(
val playlistId: String,
val identifier: String
)
My DAO for the link table is as follows:
#Dao
interface PlaylistMediaLinkDao {
#Transaction
#Query("SELECT * FROM PLAYLISTENTITY")
fun getPlaylistWithMediaItems(): List<MediaInPlaylist>
#Insert(onConflict = OnConflictStrategy.IGNORE)
fun insert(playlistMediaLinkEntity: PlaylistMediaLinkEntity)
}
And then my media in playlist object:
class MediaInPlaylist() {
#Embedded
lateinit var playlist: PlaylistEntity
#Relation(
parentColumn = "playlistId",
entity = MediaEntity::class,
entityColumn = "identifier",
associateBy = Junction(
value = PlaylistMediaLinkEntity::class,
parentColumn = "playlistId",
entityColumn = "identifier"
)
)
lateinit var mediaEntities: List<MediaEntity>
}
I can confirm my PlaylistMediaLinkEntity is populated with playlist-media id pairs, but when calling getAllPlaylistsWithMediaItems, the MediaInPlaylist object is returned with the Playlist data, but the list of mediaEntries is empty.
Have I left something out or where am I going wrong? What I've done matches most examples online.

Categories

Resources