ROOM database entity modeling - android

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

Related

Android Room: Resolve foreign key in query

Given the following data model (i.e. one customer can have many orders and one order can have many shipments), how do I get a list of all orders with their associated customer and shipments for a certain order date?
In Kotlin, I'd like to retrieve a list of type List<OrderWithCustomerAndShipments> with OrderWithCustomerAndShipments being a POJO like this:
data class OrderWithCustomerAndShipments(
val order: Order,
val category: Category,
val shipments: List<Shipment>
)
Approach
So far, I've got a method that returns a List<OrderWithShipments>.
Note: For brevity, I omit #TypeConverter
, #ForeignKey, #ColumnInfo, etc.
#Dao
interface Dao {
#Transaction
#Query("SELECT * FROM orders WHERE orderDate = :date")
fun getOrdersWithShipments(date: Date): LiveData<List<OrderWithShipments>>
}
data class OrderWithShipments(
#Embedded
val order: Order
#Relation(parentColumn = "id", entityColumn = "orderId")
val shipments = List<Shipment>
)
#Entity
data class Customer(
#PrimaryKey val id: Int,
val customerName: String
)
#Entity
data class Order(
#PrimaryKey val id: Int,
val customerId: Int,
val orderDate: Date,
)
#Entity
data class Order(
#PrimaryKey val id: Int,
val orderId: Int,
val shipmentDate: Date,
)
One would assume that it is easier to resolve an order's foreign key to the parent customer than to get all child shipments. However, my attempts to get the parent customer haven't been successful so far.
Have you tried approach below? You could use several #Relation in Room
#Dao
interface Dao {
#Transaction
#Query("SELECT * FROM orders WHERE orderDate = :date")
fun getOrdersWithCustomerAndShipments(date: Date): LiveData<List<OrderWithCustomerAndShipments>>
}
data class OrderWithCustomerAndShipments(
#Embedded
val order: Order
#Relation(parentColumn = "customerId", entityColumn = "id")
val customer: Customer
#Relation(parentColumn = "id", entityColumn = "orderId")
val shipments: List<Shipment>
)

Room #Relation with nested dynamic WHERE clause

Suppose I have items which can each have many categories:
#Entity(tableName = "items")
data class Item(
#PrimaryKey val item_id: Long,
val external_id: String,
val name: String,
val price: Long,
val image: String?,
var indexInResponse: Int = -1
)
#Entity(tableName = "categories")
data class Category(
#PrimaryKey val cat_id: Long,
val name: String,
val image: String?,
var indexInResponse: Int = -1
)
//-------
#Entity(tableName = "items_with_categories", primaryKeys = ["item", "cat"], indices = [Index(value = ["cat"])])
data class ItemCategoryCrossRef(
val item: Long,
val cat: Long
)
data class ItemWithCategories(
#Embedded val item: Item,
#Relation(
parentColumn = "item_id",
entityColumn = "cat_id",
associateBy = Junction(
ItemCategoryCrossRef::class,
parentColumn = "item",
entityColumn = "cat")
)
val cats: List<Category>
)
And I can retrieve all items with categories using this, which works well:
#Transaction
#Query("SELECT * FROM items ORDER BY indexInResponse ASC")
abstract fun getItemsWithCategories(): DataSource.Factory<Int, ItemWithCategories>
How can I retrieve items with particular categories based on ID using Room or SQL?
#Transaction
#Query("SELECT * FROM items WHERE ??<something>?? LIKE :catID ORDER BY indexInResponse ASC")
abstract fun getItemsWithCategoriesByCatID(catID: Long): DataSource.Factory<Int, ItemWithCategories>
I don't think this is possible, obviously the list of Categories is a list of POJOs, and it's a nested relation. So is the only way to do this in SQL to do it with a raw query?
This is the closest question I have found, but the DatabaseView in the answer here uses a hard coded field for it's WHERE clause and I need to be able to specify the category ID at run time.

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.

Something I am missing with many to many relationship in android room database

Following the official documentation for using #Relation and Junction tables for cross relationship between two tables and I am not having good results.
I am using these two entities:
#Entity(tableName = "Dog",
foreignKeys = arrayOf(
ForeignKey(entity = Owner::class,
parentColumns = arrayOf("ownerId"),
childColumns = arrayOf("dogOwnerId"))
))
data class Dog(
#PrimaryKey val dogId: Long,
val dogOwnerId: Long,
val name: String,
val cuteness: Int,
val barkVolume: Int,
val breed: String
)
#Entity
data class Owner(#PrimaryKey val ownerId: Long, val name: String)
using this table to join them
#Entity(primaryKeys = ["dogId", "ownerId"])
data class DogOwnerCrossRef(
val dogId: Long,
val ownerId: Long
)
and this class for the Query response:
data class DogWithOwners(
#Embedded val dog: Dog,
#Relation(
parentColumn = "dogId",
entity = Owner::class,
entityColumn = "ownerId",
associateBy = Junction(DogOwnerCrossRef::class)
)
val owners: List<Owner>
)
My DAO:
#Transaction
#Query("SELECT * FROM Dog")
fun getdogWithOwners(): List<DogWithOwners>
the result is always null for Owner objects which looks like the #Transaction haven't been made,I am puzzled on how to handle this query without making any join queries.

Room : how to implement several one-to-one relations?

I can find several examples and a good documentation on how to implement a one-to-one relation using Room, but I cannot find any documentation on how to implement several one-to-one relations.
Here an example based on this article.
If 1 dog has 1 owner, I can create a Dog entity:
#Entity
data class Dog(
#PrimaryKey val dogId: Long,
val dogOwnerId: Long,
val name: String,
val cuteness: Int,
val barkVolume: Int,
val breed: String
)
Then I can create a Owner entity:
#Entity
data class Owner(#PrimaryKey val ownerId: Long, val name: String)
Now, I can create a DogAndOwner data class in order to retrieve a dog and its owner with Room:
data class DogAndOwner(
#Embedded val owner: Owner,
#Relation(
parentColumn = "ownerId",
entityColumn = "dogOwnerId"
)
val dog: Dog
)
and the request:
#Transaction
#Query("SELECT * FROM Owner")
fun getDogsAndOwners(): List<DogAndOwner>
Now, I would like to add another one-to-one relation to my dog, for example a home.
I can create the Home entity:
#Entity
data class Home(#PrimaryKey val homeId: Long, val address: String)
and I can update my Dog entity with the dogHome attribute:
#Entity
data class Dog(
#PrimaryKey val dogId: Long,
val dogOwnerId: Long,
val dogHomeId: Long,
val name: String,
val cuteness: Int,
val barkVolume: Int,
val breed: String
)
Now, the question is, how to create a DogAndOwnerAndHome data class? I would like to write something like that:
data class DogAndOwner(
#Embedded val owner: Owner,
#Embedded val home: Home,
#Relation(
parentColumn = "ownerId",
entityColumn = "dogOwnerId"
)
#Relation(
parentColumn = "homeId",
entityColumn = "dogHomeId"
)
val dog: Dog
)
but... the Relation annotation is not repeatable so I cannot. It is possible to retrieve directly a dog, its owner and its home with Room ?
Thank you in advance for your help.
I believe that you can use :-
data class DogAndOwnerAndHome (
#Embedded
val dog: Dog,
#Relation(entity = Owner::class,parentColumn = "dogOwnerId", entityColumn = "ownerId" )
val owner: Owner,
#Relation(entity = Home::class,parentColumn = "dogHomeId", entityColumn = "homeId" )
val home: Home
)
You may wish to change the Dog and Owner entities to ensure that column names are unique e.g. :-
#Entity
data class Dog(
#PrimaryKey val dogId: Long,
val dogOwnerId: Long,
val dogHomeId: Long,
val dogname: String,
val dogcuteness: Int,
val dogbarkVolume: Int,
val dogbreed: String
)
and :-
#Entity
data class Owner(#PrimaryKey val ownerId: Long, val ownername: String)
You can then use (as an example) :-
#Transaction
#Query("SELECT * FROM Dog")
fun getAllDogsWithOwnerAndHome() : List<DogAndOwnerAndHome>
You will need one of the later versions of the room libraries e.g.
kapt 'androidx.room:room-compiler:2.2.3'
implementation 'androidx.room:room-runtime:2.2.3'
Demo/Test
Using :-
val database = Room.databaseBuilder(this,AppDatabase::class.java,"petdb")
.allowMainThreadQueries()
.build()
val homeid = database.allDao().insertHome(Home(0,"Myhouse"))
val ownerid = database.allDao().insertOwner(Owner(0,"Me"))
val dogid = database.allDao().insertDog(Dog(0,ownerid,homeid,"Woof",1,0,"terrier"))
val alldogswithownerandwithhome = database.allDao().getAllDogsWithOwnerAndHome()
for (dwoh: DogAndOwnerAndHome in alldogswithownerandwithhome) {
Log.d("DOGDETAILS","Dog name is " + dwoh.dog.dogname + " Owned By " + dwoh.owner.ownername + " Lives at " + dwoh.home.address)
}
Testing the above results in :-
D/DOGDETAILS: Dog name is Woof Owned By Me Lives at Myhouse
It sound like you need a composite key to ensure 1 to 1 relationships:
#Entity(primaryKeys = ["dog","owner"])
data class DogAndOwner(
val owner: Owner,
val home: Home,
val dog: Dog
)

Categories

Resources