Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Room basic sample in Kotlin
apply plugin: 'kotlin-kapt'
dependencies {
implementation "androidx.room:room-ktx:2.2.5"
kapt "androidx.room:room-compiler:2.2.5"
}
import androidx.room.Database
import androidx.room.RoomDatabase
@Database(
entities = [Person::class],
version = 1
)
abstract class PeopleDb : RoomDatabase() {
abstract fun personDao(): PersonDao
}
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity
data class Person(
@PrimaryKey(autoGenerate = true)
val id: Int,
val name: String,
val age: Int,
val address: String
)
import androidx.room.*
@Dao
interface PersonDao {
@Query("SELECT * from Person")
suspend fun getAll(): List<Person>
@Query("SELECT * FROM Person WHERE id = :id")
suspend fun findById(id: Int): Person
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insert(people: List<Person>)
@Update
suspend fun update(person: Person)
@Delete
suspend fun delete(person: Person)
}
import android.app.Application
import androidx.room.Room
class RoomApp : Application() {
val room: PeopleDb = Room
.databaseBuilder(this, PeopleDb::class.java, "people")
.build()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.