Created
July 7, 2020 11:14
-
-
Save antoniolg/f76f2128db897b4a2b8c3013035e631b to your computer and use it in GitHub Desktop.
Room basic sample in Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
apply plugin: 'kotlin-kapt' | |
dependencies { | |
implementation "androidx.room:room-ktx:2.2.5" | |
kapt "androidx.room:room-compiler:2.2.5" | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import androidx.room.Database | |
import androidx.room.RoomDatabase | |
@Database( | |
entities = [Person::class], | |
version = 1 | |
) | |
abstract class PeopleDb : RoomDatabase() { | |
abstract fun personDao(): PersonDao | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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