Room relation with conditions - android

I have an object Category
#Entity
data class Category(
#PrimaryKey
val id: String,
val name: String,
val is_free: Boolean
)
and object Section
#Entity
data class Section(
#PrimaryKey
val name: String,
val category_ids: List<String>
)
Sample data for Category object as below
[
{
"id": "quotes",
"name": "General",
"is_free": true
},
{
"id": "favorites",
"name": "Favorites",
"is_free": true
},
{
"id": "positivity",
"name": "Positive Thinking",
"is_free": false
},
{
"id": "love",
"name": "Love",
"is_free": false
}
]
and this the sample data for Section object
[
{
"name": "Categories",
"category_ids": [
"quotes",
"favorites"
]
},
{
"name": "Most Popular",
"category_ids": [
"positivity",
"love"
]
}
]
Now I need create new object as SectionWithCategory like below by replacing the category_ids of Section object by relevant Category object,
data class SectionWithCategories(
val name: String,
val categories: List<Category>
)
My problem is how can I create SectionWithCategories object to get following result?
[
{
"name": "Categories",
"categories": [
{
"id": "quotes",
"name": "General",
"is_free": true
},
{
"id": "favorites",
"name": "Favorites",
"is_free": true
}
]
},
{
"name": "Most Popular",
"categories": [
{
"id": "positivity",
"name": "Positive Thinking",
"is_free": false
},
{
"id": "love",
"name": "Love",
"is_free": false
}
]
}
]

My problem is how can I create SectionWithCategories object to get following result?
With some difficulty because you are, assuming that you have appropriate type converters, storing data that is not conducive to relationships and thus extracting related data.
You would have to extract the data and then build the objects from the JOSN strings that are being stored.
If you have no Type Converters then the your Section Entity will not compile as you cannot a column that has a type of List.
I would suggest, as you appear to have a many-many relationship between Sections and Categories, that you adopt a third table that holds the relationships (and does away with the need to have Type Converters).
this also does away with the bloat that comes with storing objects as JSON
So instead of having val category_ids: List<String> in the Section Entity e.g. :-
#Entity
data class Section(
#PrimaryKey
val id: String,
val name: String,
//val category_ids: List<String> use mapping/associatetive table instead
)
commented out but should probably be removed.
You remove this line and have a third Entity that stores the id of the Section and the respective id of the category allowing for any combination. The following is a full version with suggested options added such as Foreign Key definitions:-
#Entity(
primaryKeys = ["sectionMap","categoryMap"] /* MUST have a primary key */
/* Foreign Keys are optional, BUT enforce referential integrity */
/* A Foreign Key is a rule that says that a child must have a parent */
/* If the rule is broken then a Foreign Key conflict results */
, foreignKeys = [
/* Defining the Section's id as the parent and the SectionMap as the child */
ForeignKey(
entity = Section::class,
parentColumns = ["id"],
childColumns = ["sectionMap"],
/* Optional within a Foreign Key are the following two Actions that can
onDelete - action to be taken if the parent is deleted
CASCADE will delete the rows that are a child of the parent
onUpdate - action taken if the value of the parent's mapped column changes
CASCADE will update the rows that are a child of the parent
*/
onDelete = ForeignKey.CASCADE,
onUpdate = ForeignKey.CASCADE
),
/* Defining the Category's id as the parent and the CategoryMap as the child */
ForeignKey(
entity = Category::class,
parentColumns = ["id"],
childColumns = ["categoryMap"],
onDelete = ForeignKey.CASCADE,
onUpdate = ForeignKey.CASCADE
)
]
)
data class SectionCategoryMap(
val sectionMap: String,
#ColumnInfo(index = true) /* Room warns if not indexed */
val categoryMap: String
)
Some notes, as comments, have been added, which should be read and perhaps investigated further.
Now your SectionWithCategories could be :-
data class SectionWithCategories(
#Embedded
val section: Section,
#Relation(
entity = Category::class, parentColumn = "id", entityColumn = "id",
associateBy = Junction(
value = SectionCategoryMap::class, /* The mapping/associative table Entity */
parentColumn = "sectionMap", /* The column that maps to the parent (Section) */
entityColumn = "categoryMap" /* The column that maps to the children (Categories) */
)
)
val categories: List<Category>
)
Demonstration
With and #Dao class (AllDao) such as :-
#Dao
abstract class AllDao {
#Insert(onConflict = IGNORE)
abstract fun insert(category: Category): Long
#Insert(onConflict = IGNORE)
abstract fun insert(section: Section): Long
#Insert(onConflict = IGNORE)
abstract fun insert(sectionCategoryMap: SectionCategoryMap): Long
#Transaction
#Query("SELECT * FROM section")
abstract fun getAllSectionWithCategories(): List<SectionWithCategories>
}
onConflict IGNORE has been coded for the inserts so that duplicates are ignored without an exception occurring so the following code is rerunnable
Long will be the rowid (a normally hidden column), it will be -1 if the insert was ignored.
Assuming a pretty standard #Database class (other than using allowMainThreadQueries, for brevity and convenience of the demo) was used, it being :-
#Database(
entities = [
Category::class,
Section::class,
SectionCategoryMap::class
],
version = DBVERSION
)
abstract class TheDatabase: RoomDatabase() {
abstract fun getAllDao(): AllDao
companion object {
const val DBVERSION = 1
const val DBNAME = "my.db"
#Volatile
private var instance: TheDatabase? = null
fun getInstance(context: Context): TheDatabase {
if (instance == null) {
instance = Room.databaseBuilder(
context,
TheDatabase::class.java,
DBNAME
)
.allowMainThreadQueries()
.build()
}
return instance as TheDatabase
}
}
}
Then in an activity the following :-
db = TheDatabase.getInstance(this)
dao = db.getAllDao();
dao.insert(Category("quotes","General",true))
dao.insert(Category("favorites","Favorites",true))
dao.insert(Category("positivity","Positive Thinking", false))
dao.insert(Category("love","Love",false))
dao.insert(Section("Section1","Section1"))
dao.insert(Section("Section2","Section2"))
dao.insert(Section("Bonus","Bonus Section"))
dao.insert(SectionCategoryMap("Section1","quotes"))
dao.insert(SectionCategoryMap("Section1","favorites"))
dao.insert(SectionCategoryMap("Section2","positivity"))
dao.insert(SectionCategoryMap("Section2","love"))
/* Extra Data */
dao.insert(SectionCategoryMap("Bonus","love"))
dao.insert(SectionCategoryMap("Bonus","favorites"))
dao.insert(SectionCategoryMap("Bonus","positivity"))
dao.insert(SectionCategoryMap("Bonus","quotes"))
dao.insert(Section("Empty","Section with no Categories"))
val TAG = "DBINFO"
for(swc: SectionWithCategories in dao.getAllSectionWithCategories()) {
Log.d(TAG,"Section is ${swc.section.name} ID is ${swc.section.id} categories are:-")
for (c: Category in swc.categories) {
Log.d(TAG,"\tCategory is ${c.name} ID is ${c.id} IS FREE is ${c.is_free}")
}
}
inserts the Categories as per your data
inserts the Sections, the two as per your data and another two
inserts the SectionCategoryMap rows that reflects your data and also additional mappings for the two new Sections (Bonus Section maps to all Categories, Empty Section maps to no Categoires).
Extracts all the Sections with the respective Categories as SectionWithCategories objects and writes the result to the log.
The result output to the log being:-
2021-10-03 09:05:04.250 D/DBINFO: Section is Section1 ID is Section1 categories are:-
2021-10-03 09:05:04.250 D/DBINFO: Category is Favorites ID is favorites IS FREE is true
2021-10-03 09:05:04.251 D/DBINFO: Category is General ID is quotes IS FREE is true
2021-10-03 09:05:04.251 D/DBINFO: Section is Section2 ID is Section2 categories are:-
2021-10-03 09:05:04.251 D/DBINFO: Category is Love ID is love IS FREE is false
2021-10-03 09:05:04.251 D/DBINFO: Category is Positive Thinking ID is positivity IS FREE is false
2021-10-03 09:05:04.251 D/DBINFO: Section is Bonus Section ID is Bonus categories are:-
2021-10-03 09:05:04.251 D/DBINFO: Category is Favorites ID is favorites IS FREE is true
2021-10-03 09:05:04.251 D/DBINFO: Category is Love ID is love IS FREE is false
2021-10-03 09:05:04.251 D/DBINFO: Category is Positive Thinking ID is positivity IS FREE is false
2021-10-03 09:05:04.251 D/DBINFO: Category is General ID is quotes IS FREE is true
2021-10-03 09:05:04.251 D/DBINFO: Section is Section with no Categories ID is Empty categories are:-
If you really want the data as JSON then you could use :-
for(swc: SectionWithCategories in dao.getAllSectionWithCategories()) {
Log.d(TAG, " SECTION JSON = ${Gson().toJson(swc.section)} CATEGROIES JSON = ${Gson().toJson(swc.categories)}")
}
in which case the output would be :-
2021-10-03 09:24:34.954 D/DBINFO: SECTION JSON = {"id":"Section1","name":"Section1"} CATEGROIES JSON = [{"id":"favorites","is_free":true,"name":"Favorites"},{"id":"quotes","is_free":true,"name":"General"}]
2021-10-03 09:24:34.956 D/DBINFO: SECTION JSON = {"id":"Section2","name":"Section2"} CATEGROIES JSON = [{"id":"love","is_free":false,"name":"Love"},{"id":"positivity","is_free":false,"name":"Positive Thinking"}]
2021-10-03 09:24:34.960 D/DBINFO: SECTION JSON = {"id":"Bonus","name":"Bonus Section"} CATEGROIES JSON = [{"id":"favorites","is_free":true,"name":"Favorites"},{"id":"love","is_free":false,"name":"Love"},{"id":"positivity","is_free":false,"name":"Positive Thinking"},{"id":"quotes","is_free":true,"name":"General"}]
2021-10-03 09:24:34.962 D/DBINFO: SECTION JSON = {"id":"Empty","name":"Section with no Categories"} CATEGROIES JSON = []

Related

Cannot build relations in Room database

I have a problem with my Room database. It consists of 2 tables "cast", "movie" and one-to-one relation "movie_cast". When I try to build a project the following errors occur:
error: Entities cannot have relations.
public final class MovieWithCastDbModel {
error: An entity must have at least 1 field annotated with #PrimaryKey
public final class MovieWithCastDbModel {
When I remove #Entity annotation from MovieWithCastDbModel class I get the following
error: Entity class must be annotated with #Entity
public final class MovieWithCastDbModel {
So whatever I do it tells me to do the opposite thing.
Here are the data classes themselves:
#Entity(tableName = "cast")
data class CastDbModel(
#PrimaryKey(autoGenerate = false)
var id : Int,
var name: String,
var profile_path: String,
var character: String)
#Entity(tableName = "movie")
#TypeConverters(IntConverter::class)
data class MovieDbModel(
var page: Int,
#PrimaryKey(autoGenerate = false)
var id: Int,
var poster_path: String,
var overview: String,
var title: String,
#ColumnInfo(name = "genre_ids")
var genre_ids: Genres,
var runtime: Int)
#Entity(tableName = "movie_cast")
class MovieWithCastDbModel(
#Embedded
var movie: MovieDbModel,
#Relation(
entity = CastDbModel::class,
parentColumn = "id",
entityColumn = "id"
)
var cast : CastDbModel
)
data class Genres(
#Embedded
var genre_ids: Int
)
class IntConverter {
#TypeConverter
fun fromGenres(value: Genres): String {
return Gson().toJson(value)
}
#TypeConverter
fun toGenres(value: String): Genres {
return Gson().fromJson(value,Genres::class.java)
}
}
What could be a problem?
As the error message says. Entities cannot have #Relation annotation.
A relation is not actually defined within a table (#Entity annotated class), they are independent unless you say otherwise by using Foreign Key constraints to enforce referential integrity (that children must have a parent).
Rather if you want to use a relationship, then you create a POJO class that can combine the data of the related tables.
What you have is a Cast table and a Movie table. The MovieCast table appears to be what is called an associative table (mapping table, reference table and other names). It caters for a many-many relationship. That is a Movie can have many related casts and a cast can be related to many Movies.
So for MovieWithCastDbModel you want something like:-
#Entity(
tableName = "movie_cast",
primaryKeys = ["movieIdMap","castIdMap"],
/* Optional Foreign Key constraints */
foreignKeys = [
/* A MovieId MUST be a value of an existing id column in the movie table */
ForeignKey(
entity = MovieDbModel::class,
parentColumns = ["id"],
childColumns = ["movieIdMap"],
/* Optional (helps maintain referential integrity) */
/* if parent is deleted then children rows of that parent are deleted */
onDelete = ForeignKey.CASCADE,
/* if parent column is changed then the column that references the parent is changed to the same value */
onUpdate = ForeignKey.CASCADE
),
ForeignKey(
entity = CastDbModel::class,
parentColumns = ["id"],
childColumns = ["castIdMap"],
onDelete = ForeignKey.CASCADE,
onUpdate = ForeignKey.CASCADE
)
]
)
data class MovieWithCastDbModel(
var movieIdMap: Int,
#ColumnInfo(index = true)
var castIdMap: Int
)
probably better to call it MovieCast or MoviesCastMap rather than MovieWithCast.
Now to allow MoviesWithCast's to be extracted you then have a POJO using #Embedded for the MovieDbModel and an #Relation that defines the association table.
So something like:-
data class MovieWithListOfCast(
#Embedded /* The parent */
var movie: MovieDbModel,
#Relation(
entity = CastDbModel::class, /* The class of the related table(entity) (the children)*/
parentColumn = "id", /* The column in the #Embedded class (parent) that is referenced/mapped to */
entityColumn = "id", /* The column in the #Relation class (child) that is referenced (many-many) or references the parent (one(parent)-many(children)) */
/* For the mapping table */
associateBy = Junction(
value = MovieWithCastDbModel::class, /* The class of the mapping table */
parentColumn = "movieIdMap", /* the column in the mapping table that maps/references the parent (#Embedded) */
entityColumn = "castIdMap" /* the column in the mapping table that maps/references the child (#Relation) */
)
)
var castList: List<CastDbModel>
)
If you then have a function in an #Dao annotated interface/asbtract class such as
#Transaction
#Query("SELECT * FROM movie")
fun getAllMoviesWithCastList(): List<MovieWithListOfCast>
The it will retrieve all the Movies with the related cast, as a list of MovieWithListOfCast objects (one per movie).
Room uses the annotations within the MovieWithListOfCast to extract ALL of the related cast. It does this with an underlying query run for each Movie and hence why #transaction should be used.

How to query a list inside Room database in android?

This is the class that i'm saving inside room database:
#Entity
data class Person(
val name : String = "Bruno",
val age : Int = 23,
#PrimaryKey(autoGenerate = true) val id: Int = 0,
val hobbies : ArrayList<String> = arrayListOf("Basquete","Academia","Musica","Anatomia")
)
I already added type converters so it is saving successfully.
What i want is to query results by what the hobbies list has. E.g:
select * from person where hobbies in ("Basquete")
I wanted to select all person objects that has "Basquete" inside the hobbies list, but this query is returning empty. What am i doing wrong?
Their is no concept of a list in a row of a table, a column holds a single value.
Having a Type Converter will store the list of hobbies as a single value (column), as such IN will check the entire (the EXACT) value (the full list and whatever encoding is used, this dependant upon the Type Converter that converters the list to the single value).
As such it is likely that using IN, is not going to be of use.
As an example the TypeConverter may convert to something along the lines of ["Basquete","Academia","Musica"] (conversion to JSON string via com.google.code.gson dependcy)
To demonstrate using data loaded and using App Inspection then with
:-
Now consider an adaptation of your query, it being SELECT *, hobbies in ("Basquete") AS TEST1, hobbies IN ('Basquete') AS TEST2, "Basquete" IN(hobbies) AS TEST3,'Basquete' IN (hobbies) AS TEST4 ,hobbies LIKE '%Basquete%' AS TEST5 FROM person WHERE person.id = 1;
Then via App Inspection, the result is
So you could use WHERE hobbies LIKE '%Basquete%'
NOTE the enclosing single quotes, which delineates sting values, (not double quotes).
note searches with the % char as the first character will result in an in-efficient scan for the data.
This assumes that the TypeConverter is converting the List of Hobbies to a String representation of the data. If the TypeConverter converted the list to a byte-stream (e.g. ByteArray) then the above would not work.
However, if you are looking for multiple hobbies, then the complexity increases. e.g. WHERE hobbies LIKE '%Basquete%' OR hobbies LIKE '%Academia%' (to find those with either, using AND instead of OR would return only those with both).
The more correct solution where IN could be utilised would be to have a table that contains the hobbies and as the relationship would be a many-many relationship (a person could have many hobbies and people could have the same hobbies) have a third mapping table for the many-many relationship.
Example of the More Correct way
All the #Entity annotated classes and also a POJO for getting a Person with their list of hobbies:-
#Entity
data class Person(
val name : String = "Bruno",
val age : Int = 23,
#PrimaryKey(autoGenerate = true) val id: Int = 0,
//val hobbies : ArrayList<String> = arrayListOf("Basquete","Academia","Musica","Anatomia") /*<<<<<<<<<< no need */
/* Also no need for type converters */
)
/* The suggested (more correct) Hobby table */
#Entity(
indices = [
Index(value = ["hobbyName"], unique = true)
]
)
data class Hobby(
#PrimaryKey
var hobbyId: Long?=null,
var hobbyName: String /* UNIQUE Index so no duplicated hobby names */
)
/* The Mapping Table
Note also know as reference table, associative table and other names
*/
/* POJO for extracting a Person with thier list of Hobbies */
data class PersonWithHobbies(
#Embedded
var person: Person,
#Relation(
entity = Hobby::class,
parentColumn = "id",
entityColumn = "hobbyId",
associateBy = Junction(
value = PersonHobbyMap::class,
parentColumn = "personIdMap",
entityColumn = "hobbyIdMap"
)
)
var hobbies: List<Hobby>
)
/* This is the Mapping Table that maps people to hobbies */
#Entity(
primaryKeys = ["personIdMap","hobbyIdMap"],
/* Option but suggested foreign key constraint definitions to enforce and maintain referential integrity
*/
foreignKeys = [
/* For the reference to the Person */
ForeignKey(
entity = Person::class, /* The parent #Entity annotated class */
parentColumns = ["id"], /* The column in the parent that is referenced */
childColumns = ["personIdMap"], /* the column in this table that holds the reference to the parent */
onDelete = ForeignKey.CASCADE, /* will delete rows in the table if the parent is deleted */
onUpdate = ForeignKey.CASCADE /* will update the value, if the value (id) in the parent is changed */
),
/* For the reference to the Hobby */
ForeignKey(
entity = Hobby::class,
parentColumns = ["hobbyId"],
childColumns = ["hobbyIdMap"],
onDelete = ForeignKey.CASCADE,
onUpdate = ForeignKey.CASCADE
)
]
)
data class PersonHobbyMap(
var personIdMap: Long,
#ColumnInfo(index = true) /* more efficient to have index on the 2nd column (first is indexed as first part of the Primary key) */
var hobbyIdMap: Long
)
refer to the comments
An #Dao annotated interface with functions to insert data and also to extract persons (with and without their hobbies) if they have any of the hobbies passed (a query for using the hobby id's and another for using the hobby names)
note that the way that Room works ALL hobbies are retrieved per person (for the first 2 queries) that is extracted.
:-
#Dao
interface TheDaos {
/* Inserts */
#Insert(onConflict = OnConflictStrategy.IGNORE)
fun insert(person: Person): Long
#Insert(onConflict = OnConflictStrategy.IGNORE)
fun insert(hobby: Hobby): Long
#Insert(onConflict = OnConflictStrategy.IGNORE)
fun insert(personHobbyMap: PersonHobbyMap): Long
/* Query for retrieving the Person and their hobbies if they have hobbies according to the provided list of hobbyId's */
#Transaction
#Query("SELECT DISTINCT person.* FROM person JOIN personHobbyMap ON person.id = personHobbyMap.personIdMap JOIN hobby ON personHobbyMap.hobbyIdMap = hobby.hobbyId WHERE hobbyId IN(:hobbyIdList);")
fun getPersonsWithHobbiesIfHobbiesInListOfHobbyIds(hobbyIdList: List<Long>): List<PersonWithHobbies>
/* Query for retrieving the Person and their hobbies if they have hobbies according to the provided list of hobby names's */
#Transaction
#Query("SELECT DISTINCT person.* FROM person JOIN personHobbyMap ON person.id = personHobbyMap.personIdMap JOIN hobby ON personHobbyMap.hobbyIdMap = hobby.hobbyId WHERE hobbyName IN(:hobbyNameList);")
fun getPersonsWithHobbiesIfHobbiesInListOfHobbyNames(hobbyNameList: List<String>): List<PersonWithHobbies>
/* The equivalent of the above 2 queries BUT only gets the Person (without Hobbies) */
#Query("SELECT DISTINCT person.* FROM person JOIN personHobbyMap ON person.id = personHobbyMap.personIdMap JOIN hobby ON personHobbyMap.hobbyIdMap = hobby.hobbyId WHERE hobbyId IN(:hobbyIdList);")
fun getPersonsIfHobbiesInListOfHobbyIds(hobbyIdList: List<Long>): List<Person>
#Query("SELECT DISTINCT person.* FROM person JOIN personHobbyMap ON person.id = personHobbyMap.personIdMap JOIN hobby ON personHobbyMap.hobbyIdMap = hobby.hobbyId WHERE hobbyName IN(:hobbyNameList);")
fun getPersonsIfHobbiesInListOfHobbyNames(hobbyNameList: List<String>): List<Person>
/* NOTE
without DISTINCT or without only selecting the columns for the Person only,
if a Person has multiple matches then that person would be extracted multiple times.
*/
}
The #Database annotated class (note .allowMainThreadQueries used for brevity and convenience):-
#Database(entities = [Person::class,Hobby::class,PersonHobbyMap::class], exportSchema = false, version = 1)
abstract class TheDatabase: RoomDatabase() {
abstract fun getTheDaos(): TheDaos
companion object {
private var instance: TheDatabase? = null
fun getInstance(context: Context): TheDatabase {
if (instance==null) {
instance = Room.databaseBuilder(context,TheDatabase::class.java,"the_database.db")
.allowMainThreadQueries()
.build()
}
return instance as TheDatabase
}
}
}
Finally activity code that puts it all together, adding some data and then querying the data selecting only the Person (with and then without their list of hobbies) :-
class MainActivity : AppCompatActivity() {
lateinit var db: TheDatabase
lateinit var dao: TheDaos
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
db = TheDatabase.getInstance(this)
dao = db.getTheDaos()
val h1 = dao.insert(Hobby(hobbyName = "Basquete"))
val h2 = dao.insert(Hobby(hobbyName = "Academia"))
val h3 = dao.insert(Hobby(hobbyName = "Musica"))
val h4 = dao.insert(Hobby(hobbyName = "Anatomia"))
val h5 = dao.insert(Hobby(hobbyName = "other"))
val h6 = dao.insert(Hobby(hobbyName = "another"))
val h7 = dao.insert(Hobby(hobbyName = "yet another"))
val p1 = dao.insert(Person(name = "Bruno", age = 23))
val p2 = dao.insert(Person(name = "Sarah", age = 21))
val p3 = dao.insert(Person(name = "Tom", age = 22))
val p4 = dao.insert(Person(name = "Mary", age = 20))
val p5 = dao.insert(Person(name = "Freda", age = 19))
/* Bruno has hobbies Basquete, Academia, Musica and Anatomia */
dao.insert(PersonHobbyMap(p1,h1))
dao.insert(PersonHobbyMap(p1,h2))
dao.insert(PersonHobbyMap(p1,h3))
dao.insert(PersonHobbyMap(p1,h4))
/* Sarah has hobbies Academia, Anatomia and another */
dao.insert(PersonHobbyMap(p2,h2))
dao.insert(PersonHobbyMap(p2,h4))
dao.insert(PersonHobbyMap(p2,h6))
/* Tom has hobbies Basquete, Musica, other and yet another */
dao.insert(PersonHobbyMap(p3,h1))
dao.insert(PersonHobbyMap(p3,h3))
dao.insert(PersonHobbyMap(p3,h5))
dao.insert(PersonHobbyMap(p4,h7))
/* Mary has hobbies other, another and yet another */
dao.insert(PersonHobbyMap(p4,h5))
dao.insert(PersonHobbyMap(p4,h6))
dao.insert(PersonHobbyMap(p4,h7))
/* Freda has no Hobbies */
val sb: StringBuilder = java.lang.StringBuilder()
/* Persons and their hobbies for those that have Basquete or Academia in their list of hobbies (hobbies to include via list of hobbyId's)*/
/* i.e. Bruno (both) and Sarah (Academia) and Tom (both) */
for(pwh in dao.getPersonsWithHobbiesIfHobbiesInListOfHobbyIds(listOf(h1,h2))) {
sb.clear()
for (h in pwh.hobbies) {
sb.append("\n\t${h.hobbyName}")
}
Log.d("DBINFO_TEST1","Person is ${pwh.person.name} and has ${pwh.hobbies.size} hobbies. They are:- ${sb}")
}
/* Persons and their hobbies for those that have Basquete or Musica in their list of hobbies (hobbies to include via list of Hobby names)*/
/* i.e. Bruno (both) and Tom (Musica) */
for(pwh in dao.getPersonsWithHobbiesIfHobbiesInListOfHobbyNames(listOf("Basquete","Musica"))) {
sb.clear()
for (h in pwh.hobbies) {
sb.append("\n\t${h.hobbyName}")
}
Log.d("DBINFO_TEST2","Person is ${pwh.person.name} and has ${pwh.hobbies.size} hobbies. They are:- ${sb}")
}
}
}
Result of running the above (i.e. output to the log) :-
2022-07-28 09:35:36.954 D/DBINFO_TEST1: Person is Bruno and has 4 hobbies. They are:-
Basquete
Academia
Musica
Anatomia
2022-07-28 09:35:36.954 D/DBINFO_TEST1: Person is Tom and has 3 hobbies. They are:-
Basquete
Musica
other
2022-07-28 09:35:36.954 D/DBINFO_TEST1: Person is Sarah and has 3 hobbies. They are:-
Academia
Anatomia
another
2022-07-28 09:35:36.958 D/DBINFO_TEST2: Person is Bruno and has 4 hobbies. They are:-
Basquete
Academia
Musica
Anatomia
2022-07-28 09:35:36.959 D/DBINFO_TEST2: Person is Tom and has 3 hobbies. They are:-
Basquete
Musica
other
In addition to utilising the IN expression/clause, this recommended way of storing the data, although a little more complex, offers advantages (at least from a relational database perspective) such as:-
the reduction of bloat (the space taken up by the additional data on converting to/from JSON strings such as delimiters)
The data is normalised from a data redundancy aspect e.g. instead of storing Basquete n times it is stored just once and referenced.
if referenced by rowid (in short and integer primary key, as per the example) then SQLite accessing such data via the index is up to twice as fast.
might be unnoticeable for a small amount of data
there will likely be increased efficiency due to the reduced space usage (more data can be buffered)
storage space taken up will be less or will contain more data for the same size (SQLite stores chunks of data which may contain free space)

What do #Relation classes mean when creating a one-to-many relationship in Room?

I'm making an Workout log app.
One Workout has multiple sets.
I want to store this in a one-to-many relationship in Room.
In conclusion, I succeeded in saving, but I'm not sure what one class does.
All of the other example sample code uses this class, so I made one myself, but it doesn't tell me what it means.
WorkoutWithSets
data class WorkoutWithSets(
#Embedded val workout: Workout,
#Relation (
parentColumn = "workoutId",
entityColumn = "parentWorkoutId"
)
val sets: List<WorkoutSetInfo>
)
The following two entity classes seem to be sufficient to express a one-to-many relationship. (Stored in Room)
Workout
#Entity
data class Workout(
#PrimaryKey(autoGenerate = true)
var workoutId: Long = 0,
var title: String = "",
var memo: String = "",
)
It seems that the following two entity classes are sufficient enough to store a one-to-many relationship.. (stored in Room)
WorkoutSetInfo
#Entity(
foreignKeys = [
ForeignKey(
entity = Workout::class,
parentColumns = arrayOf("workoutId"),
childColumns = arrayOf("parentWorkoutId"),
onDelete = ForeignKey.CASCADE
)
]
)
data class WorkoutSetInfo(
#PrimaryKey(autoGenerate = true)
val id: Long = 0,
val set: Int,
var weight: String = "",
var reps: String = "",
var unit: WorkoutUnit = WorkoutUnit.kg,
val parentWorkoutId: Long = 0
)
Even if the WorkoutWithSet class does not exist, the Workout and WorkoutSetInfo classes are stored in Room.
What does WorkoutWithSets class mean? (or where should I use it?)
What does WorkoutWithSets class mean?
It is a class that can be used to retrieve a Workout along with all the related WorkoutSetInfos via a simple #Query that just retrieves the parent Workouts.
What Room does is add an additional query that retrieves the children (WorkoutSetInfo's) for each Workout.
The result being a list of WorkOutWithSets each element (a Workout) containing/including a list of all the related WorkoutSetInfo's.
You would use this when you want to process a Workout (or many Workouts) along with the related WorkoutSetInfo's (aka the child WorkoutSetInfo's for the parent Workout).
What Room does is consider the type (objects) to be returned.
So if you had
#Query("SELECT * FROM workout")
fun getJustWorkouts(): List<Workout>
then the function would return just a list of Workout objects.
But if you had
#Query("SELECT * FROM workout")
fun getWorkoutsWithSets(): List<WorkoutWithSets>
then the function would return a list of WorkoutWithSets and thus the parent Workouts with the child WorkoutSetInfo's.
What Room does is build and execute an underlying query, for eack Workout extracted, along the lines of "SELECT * FROM workoutInfoSet WHERE workout.workoutId = parentWorkoutId" and hence why it suggests the use of the #Transaction annotation (the build will include a warning if #Transaction is not coded).

how to populate intermediate table in Android

I have two tables with a many-to-many relationship. So I created an intermediate table, but I can't find a way to populate this table correctly because I can't set a correct list from my data.
I have a list of 'courses' : each 'course' can have one or several categories.
So my table looks like this :
|idcourses|title|date|categories|
|----|----|----|----|
|700|title1|01012021|[54]|
|701|title2|01022021|[54]|
|702|title3|01032021|[48]|
|868|title4|01042021|[47, 52, 54]|
If I try a map like this :
val myMap = coursesList.map { itcategory to it.idcourses}.distinct()
I have this kind of result :
([54], 700), ([54], 701), ([48], 702), ([47, 52, 54], 868)
The whole "[47, 52, 54]" is considered as one string but I want it to be split so I can have this :
([54], 700), ([54], 701), ([48], 702), ([47], 868), ([52], 868), ([54], 868)
Does anyone know how to achieve this ??
I believe that you may be trying to do this the wrong way as it appears that your intermediate table has a column where you are expecting a list of category id's.
You cannot have a column that is a list/array it has to be a single object.
However rather than try to fix that, what would typically be used for an intermediate table is a table that primarily has a single row per mapping. That is two columns that make up a mapping. Where the two columns are a composite primary key.
other columns that have data specific to the mapping can be used.
In your case one column to map/reference/relate/associate to the course and an second column to map the course.
For example, say you have the Course Table and the Category Table per:-
#Entity
data class Course(
#PrimaryKey
val idcourses: Long? = null,
val title: String,
val date: String
)
and
#Entity
data class Category(
#PrimaryKey
val idcategories: Long? = null,
val name: String
)
Then you could have the intermediate table as :-
#Entity(primaryKeys = ["idcoursesmap","idcategoriesmap"])
data class CourseCategoryMap(
val idcoursesmap: Long,
#ColumnInfo(index = true)
val idcategoriesmap: Long
)
the index on the idcategoriesmap will likely improve the efficiency. Room would also issue a warning.
you may wish to consider defining Foreign Key constraints to enforce referential integrity. None have been included for brevity.
This is sufficient for a many-many relationship.
You would probably want to retrieve Courses with the Categories so you would probably want a POJO for this such as:-
data class CourseWithCategories(
#Embedded
val course: Course,
#Relation(
entity = Category::class,
parentColumn = "idcourses",
entityColumn = "idcategories",
associateBy = Junction(
value = CourseCategoryMap::class,
parentColumn = "idcoursesmap",
entityColumn = "idcategoriesmap"
)
)
val categories: List<Category>
)
Here's some Dao's that would or may be wanted/useful:-
abstract class AllDao {
#Insert(onConflict = IGNORE) // Insert single Category
abstract fun insert(category: Category): Long
#Insert(onConflict = IGNORE) // Insert Single Course
abstract fun insert(course: Course): Long
#Insert(onConflict = IGNORE) // Insert Single CourseCategoryMap
abstract fun insert(courseCategoryMap: CourseCategoryMap): Long
/* Inserts many course category maps */
#Insert(onConflict = IGNORE)
abstract fun insert(courseCategoryMaps: List<CourseCategoryMap>): List<Long>
#Query("SELECT * FROM course WHERE course.title=:courseTitle")
abstract fun getCourseByTitle(courseTitle: String): Course
#Query("SELECT * FROM category WHERE category.name LIKE :categoryMask")
abstract fun getCategoriesByNameMask(categoryMask: String): List<Category>
/* For retrieving courses with all the courses categories */
#Transaction
#Query("SELECT * FROM course")
abstract fun getAllCoursesWithCategories(): List<CourseWithCategories>
#Transaction
#Query("")
fun insertManyCataegoriesForACourseByIds(idcourse: Long,categories: List<Long>) {
for (categoryId: Long in categories) {
insert(CourseCategoryMap(idcourse,categoryId))
}
}
// Anoher possibility
#Transaction
#Query("")
fun insertManyCategoriesForACourse(course: Course, categories: List<Category>) {
val categoryIds = ArrayList<Long>()
for (c: Category in categories) {
categoryIds.add(c.idcategories!!)
}
insertManyCataegoriesForACourseByIds(course.idcourses!!,categoryIds)
}
}
Demonstration
To demonstrate the above, a pretty standard class annotated with #Database :-
const val DATABASE_NAME = "the_database.db"
const val DATABASE_VERSION =1
#Database(entities = [Course::class,Category::class,CourseCategoryMap::class], exportSchema = false, version = DATABASE_VERSION)
abstract class TheDatabase: RoomDatabase() {
abstract fun getAllDao(): AllDao
companion object {
#Volatile
private var instance: TheDatabase? = null
fun getInstance(context: Context): TheDatabase {
if (instance == null) {
instance = Room.databaseBuilder(context,TheDatabase::class.java, DATABASE_NAME)
.allowMainThreadQueries()
.build()
}
return instance as TheDatabase
}
}
}
And activity code to replicate what it looks like your are attempting (but twice to show 2 ways of mapping, the second using category id's that are 20 greater then the first) :-
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()
dao.insert(Course(idcourses = 700,title = "title1", date = "01012021"))
dao.insert(Course(701,"title2","01022021"))
dao.insert(Course(702,"title3","01032021"))
dao.insert(Course(868,"title4","01042021"))
// add quite a few categories for demo
for(i in 30..300) {
dao.insert(Category(i.toLong(),"Category${i}"))
}
//example of what you are trying to do (first)
var currentCourse = dao.getCourseByTitle("title1")
dao.insertManyCataegoriesForACourseByIds(currentCourse.idcourses!!, listOf(54))
dao.insertManyCataegoriesForACourseByIds(dao.getCourseByTitle("title2").idcourses!!, listOf(54))
dao.insertManyCataegoriesForACourseByIds(dao.getCourseByTitle("title3").idcourses!!, listOf(48))
dao.insertManyCataegoriesForACourseByIds(dao.getCourseByTitle("title4").idcourses!!, listOf(47,52,54))
// second (does the same but uses categroyids 20 greater than the first)
val coursecategorymaplist = listOf<CourseCategoryMap>(
CourseCategoryMap(700,74),
CourseCategoryMap(701,74),
CourseCategoryMap(702,68),
CourseCategoryMap(868,67),
CourseCategoryMap(868,72),
CourseCategoryMap(868,74)
)
dao.insert(coursecategorymaplist)
// Extract results
for (cwc: CourseWithCategories in dao.getAllCoursesWithCategories()) {
Log.d("DBINFO","Course is ${cwc.course.title}, date is ${cwc.course.date} it has ${cwc.categories.size} categories they are:-")
for (c: Category in cwc.categories) {
Log.d("DBINFO","\tCategory is ${c.name}")
}
}
}
Results
The log includes (note double the number of categories):-
D/DBINFO: Course is title1, date is 01012021 it has 2 categories they are:-
D/DBINFO: Category is Category54
D/DBINFO: Category is Category74
D/DBINFO: Course is title2, date is 01022021 it has 2 categories they are:-
D/DBINFO: Category is Category54
D/DBINFO: Category is Category74
D/DBINFO: Course is title3, date is 01032021 it has 2 categories they are:-
D/DBINFO: Category is Category48
D/DBINFO: Category is Category68
D/DBINFO: Course is title4, date is 01042021 it has 6 categories they are:-
D/DBINFO: Category is Category47
D/DBINFO: Category is Category52
D/DBINFO: Category is Category54
D/DBINFO: Category is Category67
D/DBINFO: Category is Category72
D/DBINFO: Category is Category74
The Database
The Course Table :-
The Category Table (partial)
The CourseCategoryMap (intermediate table)

Insert relation in Room android

I have question how to insert relation in room. So, I have Product and ProductsList entities. ProductsList could have a lot of Products, but products shouldn't know anything about lists where are they contained.
#Entity(tableName = "products")
data class Product(
#PrimaryKey(autoGenerate = true)
val productId: Long,
val productName: String
)
#Entity
data class ProductList(
#PrimaryKey(autoGenerate = true)
val productListId: Long,
val listName: String
)
I created ProductsListWithProducts class:
data class ProductListWithProducts(
#Embedded
val productList: ProductList,
#Relation(
parentColumn = "productListId",
entityColumn = "productId",
entity = Product::class
)
val productsId: List<Product>
)
but I don't understand how to insert data in Database. For example I already added Products in its table and after it want to create new ProductList. I have checked other answers and found that for it just using Dao to insert it something like:
#Dao
abstract class ProductListDao {
#Transaction
fun insert(productList: ProductList, products: List<Product>) {
insert(productList)
for (product in products) {
insert(product)
}
}
But I don't see how adding relation between this tables, because I don't want to foreign keys in product entity (because in this case I need to create many-to-many relation). I thought about additional entity
#Entity(primaryKeys = ["productId", "productListId"])
data class ProductListProducts(
val productId: Long,
val productListId: Long
)
but it's using also to define many-to-many relation.
Can I add this relation without creating many-to-many relation, just one-to-many?
Yes have ProductListProducts however you may wish to consider using :-
#Entity(
primaryKeys = ["productId", "productListId"]
,indices = [
Index(value = ["productListId"]) /* Index else Room warns */
]
/* Foreign Keys are optional BUT enforce referential integrity */
, foreignKeys = [
ForeignKey(
entity = Product::class,
parentColumns = ["productId"],
childColumns = ["productId"],
onDelete = ForeignKey.CASCADE,
onUpdate = ForeignKey.CASCADE
),
ForeignKey(
entity = ProductList::class,
parentColumns = ["productListId"],
childColumns = ["productListId"],
onDelete = ForeignKey.CASCADE,
onUpdate = ForeignKey.CASCADE
)
]
)
data class ProductListProducts(
val productId: Long,
val productListId: Long
)
you may wish to refer to https://sqlite.org/foreignkeys.html
This is an associative table (reference table, mapping table and many other terms). So you use a Relationship that utilises the association for the Junction between the ProductList and Product. Therefore your ProductListWithProducts POJO becomes :-
data class ProductListWithProducts (
#Embedded
val productList: ProductList,
#Relation(
entity = Product::class,
parentColumn = "productListId",
entityColumn = "productId",
associateBy = Junction(
ProductListProducts::class,
parentColumn = "productListId",
entityColumn = "productId"
)
)
val product: List<Product>
)
Demonstration using the above classes (and your classes where the id's have been altered to be Long=0)
With a Dao class like :-
#Dao
abstract class AllDao {
#Insert
abstract fun insert(product: Product): Long
#Insert
abstract fun insert(productList: ProductList): Long
#Insert
abstract fun insert(productListProducts: ProductListProducts): Long
#Transaction
#Query("SELECT * FROM ProductList")
abstract fun getProductListWithProducts(): List<ProductListWithProducts>
}
Then the following (run on the main thread for brevity/convenience) :-
db = TheDatabase.getInstance(this)
dao = db.getAllDao()
var p1 = dao.insert(Product( productName = "Product1"))
var p2 = dao.insert(Product(productName = "Product2"))
var pl1 = dao.insert(ProductList(listName = "List1"))
var pl2 = dao.insert(ProductList(listName = "List2"))
dao.insert(ProductListProducts(p1,pl1))
dao.insert(ProductListProducts(p1,pl2))
dao.insert(ProductListProducts(p2,pl1))
dao.insert(ProductListProducts(dao.insert(Product(productName = "Product3")),dao.insert(
ProductList(listName = "List3")))
)
for(plwp: ProductListWithProducts in dao.getProductListWithProducts()) {
Log.d(TAG,"ProductList is ${plwp.productList.listName} ID is ${plwp.productList.productListId}")
for(p: Product in plwp.product) {
Log.d(TAG,"\t Product is ${p.productName} ID is ${p.productId}")
}
}
results in the log containing :-
D/DBINFO: ProductList is List1 ID is 1
D/DBINFO: Product is Product1 ID is 1
D/DBINFO: Product is Product2 ID is 2
D/DBINFO: ProductList is List2 ID is 2
D/DBINFO: Product is Product1 ID is 1
D/DBINFO: ProductList is List3 ID is 3
D/DBINFO: Product is Product3 ID is 3
Can I add this relation without creating many-to-many relation, just one-to-many?
The above (i.e. the associative table) will handle 1 to many but if you don't want the the extra table then you would have to include the identifier of the parent in the child. You could enforce 1-many, in the associative table, by making the column for the 1 unique.
As for Mass type insertions you say
For example I already added Products in its table and after it want to create new ProductList
Then you could perhaps go about by having the following additional #Dao's :-
#Insert
abstract fun insert(productListList: List<ProductList>): LongArray
#Insert
abstract fun insertManyProductListProducts(productListProductsList: List<ProductListProducts>): LongArray
/* This can be used to get a specific product or products according to a pattern */
/* e.g. */
/* if productPatterName is product1 then an exact match */
/* if prod% then all that start with prod */
/* if %prod all that end in prod */
/* if %prod% then all that have prod anywhere */
#Query("SELECT productId FROM products WHERE productName LIKE :productNamePattern")
abstract fun getProductIdByName(productNamePattern: String): LongArray
And then have code such as :-
/* Adding many new ProductLists to existing Products */
/* 1 add the new ProductLists */
/* Noting that the insert returns an array of the productListId's inserted */
val insertedProductLists = dao.insert(
listOf(
ProductList(listName = "ListX1"),
ProductList(listName = "ListX2")
)
)
/* 2. Determine the Product(s) that will be related to the new list of ProductLists */
val productIdList = dao.getProductIdByName("Product%") /* All products */
/* 3. Prepare the List of ProductListProducts for mass insertion */
val plplist: ArrayList<ProductListProducts> = ArrayList()
for(pid: Long in productIdList) {
for(plid: Long in insertedProductLists) {
plplist.add(ProductListProducts(pid,plid))
}
}
/* 4. add the relationships */
dao.insertManyProductListProducts(plplist)
If you wanted 1 existing product e.g. product1 then you would use dao.getProductIdByName("Product1"), of course you can also increase/reduce the productLists in the Array to suit.
This would result in :-
D/DBINFO: ProductList is List1 ID is 1
D/DBINFO: Product is Product1 ID is 1
D/DBINFO: Product is Product2 ID is 2
D/DBINFO: ProductList is List2 ID is 2
D/DBINFO: Product is Product1 ID is 1
D/DBINFO: ProductList is List3 ID is 3
D/DBINFO: Product is Product3 ID is 3
D/DBINFO: ProductList is ListX1 ID is 4
D/DBINFO: Product is Product1 ID is 1
D/DBINFO: Product is Product2 ID is 2
D/DBINFO: Product is Product3 ID is 3
D/DBINFO: ProductList is ListX2 ID is 5
D/DBINFO: Product is Product1 ID is 1
D/DBINFO: Product is Product2 ID is 2
D/DBINFO: Product is Product3 ID is 3

Categories

Resources