I have a problem with Room ORM working on Kotlin. My task is having ability to save and get data models RouteTemplateModel, that contains list of addresses of type AddressModel and object of class RouteModel that contains title of the specific route. Here is my code:
AddressModel.kt
@Entity(foreignKeys = arrayOf(
ForeignKey(entity = RouteModel::class,
parentColumns = arrayOf("routeId"),
childColumns = arrayOf("parentId"))))
data class AddressModel(
@PrimaryKey(autoGenerate = true)
var addressId: Long,
var parentId: Long,
var street: String,
var house: String,
var entrance: String,
var title: String){
constructor(): this(0, 0, "", "", "", "")
}
RouteModel.kt
@Entity
data class RouteModel(
@PrimaryKey(autoGenerate = true)
var routeId: Long,
var title: String) {
constructor() : this(0, "")
}
Here is my simple models, I found in documentation of Room that for creating relations between models I need to use @ForeignKey
and @Relation
So with code samples in doc and tutorials I create RouteTemplateModel
that contains object of RouteModel
and list of AddressModels
. Here is the class
RouteTemplateModel
class RouteTemplateModel{
private var id: Long = 0
@Embedded
private var routeModel: RouteModel = RouteModel()
@Relation(parentColumn = "routeId", entityColumn = "parentId")
private var addressList: List<AddressModel> = listOf()
constructor()
constructor(id: Long, routeModel: RouteModel, title: String,
addressList: List<AddressModel>){
this.id = id
this.routeModel = routeModel
this.addressList = addressList
}
fun getId(): Long{
return id
}
fun getRouteModel(): RouteModel{
return routeModel
}
fun getAddressList(): List<AddressModel>{
return addressList
}
fun setId(id: Long){
this.id = id
}
fun setRouteModel(routeModel: RouteModel){
this.routeModel = routeModel
}
fun setAddressList(addressList: List<AddressModel>){
this.addressList = addressList
}
}
So what`s a problem? I am getting such errors:
Error:The columns returned by the query does not have the fields [id] in com.innotech.webcab3kotlin.model.RouteTemplateModel even though they are annotated as non-null or primitive. Columns returned by the query: [routeId,title]
And
Error:Type of the parameter must be a class annotated with @Entity or a collection/array of it.
It is a real problem, because if my trying to fix first error and annotate in RouteTemplateModel
id variable to return this column too, I need annotate class as Entity (like in second error), but when I do it I am getting an error
Error:Entities cannot have relations.
Here is AppDatabase.kt
@Database(entities = arrayOf(RouteModel::class, AddressModel::class), version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun getRouteDao(): RouteDao
}
and RouteDao.kt
@Dao
interface RouteDao {
@Query("SELECT routeId, title FROM RouteModel")
fun getAll(): List<RouteTemplateModel>
@Insert
fun insertAll(vararg models: RouteTemplateModel)
@Delete
fun delete(model: RouteTemplateModel)
}
Thats really confusing. Please, help me)