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