androidkotlinandroid-roomdagger-hiltkapt

KAPT Room throws build errors


I am following main tutorial https://developer.android.com/training/data-storage/room on integrating Room, but when building it throws a lot of errors:

Entity class must be annotated with @Entity

Entities and POJOs must have a usable public constructor. You can have an empty constructor or a constructor whose parameters match the fields (by name and type).

An entity must have at least 1 field annotated with @PrimaryKey

Schema export directory is not provided to the annotation processor so we cannot export the schema. You can either provide `room.schemaLocation` annotation processor argument OR set exportSchema to false.

Entity:

@Entity(tableName = "app")
class App(@PrimaryKey val id: Long, val name: String)

Dao:

@Dao
interface AppDao {

    @Insert
    suspend fun insertApp(app: App)

}

Database:

@Database(
    entities = [AppDao::class],
    version = 1
)
abstract class MyDatabase : RoomDatabase() {
    abstract fun appDao(): AppDao
}

If I uncomment the ksp(libs.androidx.room.compiler) it does not throw build errors. Not sure how to fix this.

Library versions

hilt-android = "2.46"
junit = "4.13.2"
kotlin = "1.8.20"
kotlin-ksp = "1.8.20-1.0.11"
room = "2.6.0-alpha01"

Solution

  • Your code is almost OK, but in your database creation class, you mispelled the entity name!

    Change AppDao to App in the entities parameter in the @Database annotation:

    @Database(
        entities = [App::class],
        version = 1
    )
    abstract class MyDatabase : RoomDatabase() {
        abstract fun appDao(): AppDao
    }
    

    Bonus: You can make your App class a data class to have some useful overriden methods out of the box!