Android Room: Resolve foreign key in query - android

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>
)

Related

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 2.5 nested relationships one to one many to one

Room
I have a relationship like this
puzzle -> has one-> dialogue -> has many -> dialogue lines
I followed the instructions on
https://developer.android.com/training/data-storage/room/relationships#kotlin
but still cant get it to work
These are the error that seem to be related:
error: Cannot find the child entity column puzzleDialogueId in com.example.puzzleherexamenandroid.data.room.databaseModels.DialogueWithLinesDatabase.
Tried the following constructors but they failed to match:
PuzzleWithDialogueDatabase(com.example.puzzleherexamenandroid.data.room.databaseModels.PuzzleDatabase,com.example.puzzleherexamenandroid.data.room.databaseModels.DialogueWithLinesDatabase) -> [param:puzzle -> matched field:puzzle, param:dialogueWithLines -> matched field:unmatched]C:\Users\Jasper\StudioProjects\PuzzleHerexamenAndroid\app\build\tmp\kapt3\stubs\debug\com\example\puzzleherexamenandroid\data\room\databaseModels\PuzzleWithDialogueDatabase.java:9: error: Cannot find setter for field.
PuzzleDatabaseDao.java:12: error: Type of the parameter must be a class annotated with #Entity or a collection/array of it.
java.util.List<com.example.puzzleherexamenandroid.data.room.databaseModels.PuzzleWithDialogueDatabase> puzzle);
these are my entities
#Entity(tableName = "puzzle_table")
#Parcelize
data class PuzzleDatabase (
#PrimaryKey
val puzzleId: Int,
val title: String,
val prompt: String,
val answer: String
): Parcelable
#Entity(tableName = "dialogue_table")
#Parcelize
data class DialogueDatabase (
#PrimaryKey
val dialogueId: Int,
val prompt: String,
val char1avatar: String,
val char2avatar: String,
val puzzleDialogueId : Int
): Parcelable
#Entity(tableName = "dialogueLine_table")
#Parcelize
data class DialogueLineDatabase (
#PrimaryKey
val dialogueLineId: Int,
val line: String,
val speaking: Int,
val dialogueForeignkeyId: Int
): Parcelable
these are the classes for the relationship
data class PuzzleWithDialogueDatabase(
#Embedded val puzzle : PuzzleDatabase,
#Relation(
entity = DialogueWithLinesDatabase::class,
parentColumn = "puzzleId",
entityColumn = "puzzleDialogueId"
)
val dialogueWithLines: DialogueWithLinesDatabase
)
data class DialogueWithLinesDatabase(
#Embedded val dialogue:DialogueDatabase,
#Relation(
parentColumn = "dialogueId",
entityColumn = "dialogueForeignkeyId"
)
val dialogueLines: List<DialogueLineDatabase>
)
And this is my doa
#Dao
interface PuzzleDatabaseDao {
#Transaction
#Insert(onConflict = OnConflictStrategy.IGNORE)
fun insertAll(puzzle: List<PuzzleWithDialogueDatabase>)
#Transaction
#Query("SELECT * from puzzle_table ORDER BY puzzleId DESC")
fun getAllPuzzles(): LiveData<List<PuzzleWithDialogueDatabase>>
}
I guess you should change entity DialogueWithLinesDatabase with DialogueDatabase inside your PuzzleWithDialogueDatabase class' Releation definition:
data class PuzzleWithDialogueDatabase(
#Embedded val puzzle : PuzzleDatabase,
#Relation(
entity = DialogueDatabase::class, // <- changed
parentColumn = "puzzleId",
entityColumn = "puzzleDialogueId"
)
val dialogueWithLines: DialogueWithLinesDatabase
)
The entity property in #Relation should mention the database entity and not the relation-class. Try:
data class PuzzleWithDialogueDatabase(
#Embedded val puzzle : PuzzleDatabase,
#Relation(
entity = DialogueDatabase::class,
parentColumn = "puzzleId",
entityColumn = "puzzleDialogueId"
)
val dialogueWithLines: DialogueWithLinesDatabase
)

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.

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
)

How to store Strings that can be queried in Room?

I want to store Strings (uids) in my Room DB. I want these uids to be able to be:
Queried (check to see if a uid exists in my list of strings)
Added to (add a uid to the list of strings)
What is the most efficient way to achieve this?
Here is my skeleton to give you some context, though my understanding of Room is very basic so there will be mistakes:
#Entity(tableName = "user_data")
data class UserData(
#PrimaryKey(autoGenerate = true) val uid: Int,
#ColumnInfo(name = "matched_users") var matchedUsers: Set<String>
)
#Dao
interface UserDataDao {
// Check to see if the uid is in matchedUsers Set/List
#Query("SELECT * FROM user_data WHERE :matchId IN matched_users")
fun matchedBefore(matchId: String): Boolean
// Add uid to Set/List
#Insert(onConflict = OnConflictStrategy.ABORT)
fun addMatchUid(uid: String)
}
Any suggestions appreciated.
According to your context, it seems you want to build one-to-many relationship, to do so you can follow the bellow codes. If not let me know what exactly you want.
#Entity(tableName = "user_data")
data class UserData(
#PrimaryKey(autoGenerate = true) val uid: Int,
#ColumnInfo(name = "name") var name: String
)
#Entity(tableName = "user_matcher")
data class UserMatcher(
#PrimaryKey(autoGenerate = true) val uid: Int,
#ColumnInfo(name = "userId") var userId: Int
)
#Dao
interface UserMatcherDao {
// Check to see if the uid is in matchedUsers Set/List
#Query("SELECT m.id as mid, u.id as uid, u.name FROM user_matcher m INNER JOIN user_data u ON m.userId = u.id WHERE m.id = :matchId")
fun getMatchedUsers(matchId: Int): List<UserData>
}

Categories

Resources