Skip to content

Instantly share code, notes, and snippets.

@antoniolg
Created July 7, 2020 11:14
Show Gist options
  • Save antoniolg/f76f2128db897b4a2b8c3013035e631b to your computer and use it in GitHub Desktop.
Save antoniolg/f76f2128db897b4a2b8c3013035e631b to your computer and use it in GitHub Desktop.
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