SlideShare a Scribd company logo
Database handling
with
Room
CC4.0 Kathleen Cole
About me
Sergi Martínez
@sergiandreplace
Android GDE & dev at Schibsted Spain
Disclaimer:
All examples are
in Kotlin
What is Room?
A library to handle android
databases via an abstraction
layer
Tl,dr;
An ORM
Components
Entity
A class representing a
database row
DAO
An interface defining
how to access to db
Database
Holds definition for
DAOs and Entities
Before anything else
repositories {
jcenter()
maven { url 'https://maven.google.com' }
}
def room = '1.0.0-beta2'
implementation "android.arch.persistence.room:runtime:${room}"
kapt "android.arch.persistence.room:compiler:${room}"
Entities
Simple entity
@Entity(tableName = "products")
class ProductEntity(
@PrimaryKey() @ColumnInfo(name = "id") var id: Long,
@ColumnInfo(name = "name") var name: String,
@ColumnInfo(name = "description") var description: String,
@ColumnInfo(name = "qty") var quantity: Long
)
Simple entity
@Entity(tableName = "products")
class ProductEntity(
@PrimaryKey() @ColumnInfo(name = "id") var id: Long,
@ColumnInfo(name = "name") var name: String,
@ColumnInfo(name = "description") var description: String,
@ColumnInfo(name = "qty") var quantity: Long
)
Simple entity
@Entity(tableName = "products")
class ProductEntity(
@PrimaryKey() @ColumnInfo(name = "id") var id: Long,
@ColumnInfo(name = "name") var name: String,
@ColumnInfo(name = "description") var description: String,
@ColumnInfo(name = "qty") var quantity: Long
)
Simple entity
@Entity(tableName = "products")
class ProductEntity(
@PrimaryKey() @ColumnInfo(name = "id") var id: Long,
@ColumnInfo(name = "name") var name: String,
@ColumnInfo(name = "description") var description: String,
@ColumnInfo(name = "qty") var quantity: Long
)
Indexes
@Entity(tableName = "inventory",
indices = arrayOf(Index("provider_id", "product_id", unique = true)))
class InventoryEntity(
@PrimaryKey() var id: Long,
@ColumnInfo(name = "provider_id") var providerId: Long,
@ColumnInfo(name = "product_id") var productId: Long,
@ColumnInfo(name = "qty") var quantity: Long
)
Composed PK
@Entity(tableName = "inventory",
primaryKeys = arrayOf("provider_id", "product_id"))
class InventoryEntity(
@ColumnInfo(name = "provider_id") var providerId: Long,
@ColumnInfo(name = "product_id") var productId: Long,
@ColumnInfo(name = "qty") var quantity: Long
)
Foreign keys
@Entity(
tableName = "inventory",
foreignKeys = arrayOf(
ForeignKey(
entity = ProductEntity::class,
parentColumns = arrayOf("id"),
childColumns = arrayOf("product_id")
)
)
)
class InventoryEntity(
@PrimaryKey() var id: Long,
@ColumnInfo(name = "provider_id") var providerId: Long,
@ColumnInfo(name = "product_id") var productId: Long,
@ColumnInfo(name = "qty") var quantity: Long
)
Foreign keys
@Entity(
tableName = "inventory",
foreignKeys = arrayOf(
ForeignKey(
entity = ProductEntity::class,
parentColumns = arrayOf("id"),
childColumns = arrayOf("product_id")
)
)
)
class InventoryEntity(
@PrimaryKey() var id: Long,
@ColumnInfo(name = "provider_id") var providerId: Long,
@ColumnInfo(name = "product_id") var productId: Long,
@ColumnInfo(name = "qty") var quantity: Long
)
Foreign keys
@Entity(
tableName = "inventory",
foreignKeys = arrayOf(
ForeignKey(
entity = ProductEntity::class,
parentColumns = arrayOf("id"),
childColumns = arrayOf("product_id")
)
)
)
class InventoryEntity(
@PrimaryKey() var id: Long,
@ColumnInfo(name = "provider_id") var providerId: Long,
@ColumnInfo(name = "product_id") var productId: Long,
@ColumnInfo(name = "qty") var quantity: Long
)
Foreign keys
@Entity(
tableName = "inventory",
foreignKeys = arrayOf(
ForeignKey(
entity = ProductEntity::class,
parentColumns = arrayOf("id"),
childColumns = arrayOf("product_id")
)
)
)
class InventoryEntity(
@PrimaryKey() var id: Long,
@ColumnInfo(name = "provider_id") var providerId: Long,
@ColumnInfo(name = "product_id") var productId: Long,
@ColumnInfo(name = "qty") var quantity: Long
)
Foreign keys
@Entity(
tableName = "inventory",
foreignKeys = arrayOf(
ForeignKey(
entity = ProductEntity::class,
parentColumns = arrayOf("id"),
childColumns = arrayOf("product_id")
)
)
)
class InventoryEntity(
@PrimaryKey() var id: Long,
@ColumnInfo(name = "provider_id") var providerId: Long,
@ColumnInfo(name = "product_id") var productId: Long,
@ColumnInfo(name = "qty") var quantity: Long
)
Foreign keys
@Entity(
tableName = "inventory",
foreignKeys = arrayOf(
ForeignKey(
entity = ProductEntity::class,
parentColumns = arrayOf("id"),
childColumns = arrayOf("product_id")
)
)
)
class InventoryEntity(
@PrimaryKey() var id: Long,
@ColumnInfo(name = "provider_id") var providerId: Long,
@ColumnInfo(name = "product_id") var productId: Long,
@ColumnInfo(name = "qty") var quantity: Long
)
Nested objects
@Entity(tableName = "products")
class ProductEntity(
@PrimaryKey() @ColumnInfo(name = "id") var id: Long,
@ColumnInfo(name = "name") var name: String,
@ColumnInfo(name = "description") var description: String,
@Embedded var info: ProductInfo
)
class ProductInfo(
@ColumnInfo(name = "color") var color: String,
@ColumnInfo(name = "size") var size: String
)
products
id name description color size
Nested objects
@Entity(tableName = "products")
class ProductEntity(
@PrimaryKey() @ColumnInfo(name = "id") var id: Long,
@ColumnInfo(name = "name") var name: String,
@ColumnInfo(name = "description") var description: String,
@Embedded var info: ProductInfo
)
class ProductInfo(
@ColumnInfo(name = "color") var color: String,
@ColumnInfo(name = "size") var size: String
)
products
id name description color size
Nested objects
@Entity(tableName = "products")
class ProductEntity(
@PrimaryKey() @ColumnInfo(name = "id") var id: Long,
@ColumnInfo(name = "name") var name: String,
@ColumnInfo(name = "description") var description: String,
@Embedded var info: ProductInfo
)
class ProductInfo(
@ColumnInfo(name = "color") var color: String,
@ColumnInfo(name = "size") var size: String
)
products
id name description color size
Nested objects
@Entity(tableName = "products")
class ProductEntity(
@PrimaryKey() @ColumnInfo(name = "id") var id: Long,
@ColumnInfo(name = "name") var name: String,
@ColumnInfo(name = "description") var description: String,
@Embedded var info: ProductInfo
)
class ProductInfo(
@ColumnInfo(name = "color") var color: String,
@ColumnInfo(name = "size") var size: String
)
products
id name description color size
DAOs
Simple DAO
@Dao
interface ProductsDao {
@Insert(onConflict = REPLACE)
fun insert(productEntity: ProductEntity): Long
@Query("Select * from products")
fun getAll(): List<ProductEntity>
@Update
fun update(productEntity: ProductEntity): Int
@Delete
fun delete(productEntity: ProductEntity): Int
}
Simple DAO
@Dao
interface ProductsDao {
@Insert(onConflict = REPLACE)
fun insert(productEntity: ProductEntity): Long
@Query("Select * from products")
fun getAll(): List<ProductEntity>
@Update
fun update(productEntity: ProductEntity): Int
@Delete
fun delete(productEntity: ProductEntity): Int
}
Simple DAO
@Dao
interface ProductsDao {
@Insert(onConflict = REPLACE)
fun insert(productEntity: ProductEntity): Long
@Query("Select * from products")
fun getAll(): List<ProductEntity>
@Update
fun update(productEntity: ProductEntity): Int
@Delete
fun delete(productEntity: ProductEntity): Int
}
Row id
Simple DAO
@Dao
interface ProductsDao {
@Insert(onConflict = REPLACE)
fun insert(productEntity: ProductEntity): Long
@Query("Select * from products")
fun getAll(): List<ProductEntity>
@Update
fun update(productEntity: ProductEntity): Int
@Delete
fun delete(productEntity: ProductEntity): Int
}
Simple DAO
@Dao
interface ProductsDao {
@Insert(onConflict = REPLACE)
fun insert(productEntity: ProductEntity): Long
@Query("Select * from products")
fun getAll(): List<ProductEntity>
@Update
fun update(productEntity: ProductEntity): Int
@Delete
fun delete(productEntity: ProductEntity): Int
}
# Modified rows
Simple DAO
@Dao
interface ProductsDao {
@Insert(onConflict = REPLACE)
fun insert(productEntity: ProductEntity): Long
@Query("Select * from products")
fun getAll(): List<ProductEntity>
@Update
fun update(productEntity: ProductEntity): Int
@Delete
fun delete(productEntity: ProductEntity): Int
}
Insert
@Dao
interface ProductsDao {
@Insert(onConflict = REPLACE)
fun insert(product: ProductEntity): Long
@Insert(onConflict = REPLACE)
fun insertAll(vararg products: ProductEntity) : List<Long>
@Insert(onConflict = ROLLBACK)
fun insertTwo(product: ProductEntity, otherProduct: ProductEntity): List<Long>
@Insert(onConflict = ABORT)
fun weirdInsert(product: ProductEntity, products: List<ProductEntity>): List<Long>
}
Update
@Dao
interface ProductsDao {
@Update()
fun update(product: ProductEntity): Int
@Update()
fun update(vararg users: ProductEntity): Int
}
Delete
@Dao
interface ProductsDao {
@Delete()
fun delete(product: ProductEntity): Int
@Delete()
fun delete(vararg users: ProductEntity): Int
}
Only primary key is matched
Query
@Dao
interface ProductsDao {
@Query("Select * from products")
fun getAllAsList(): List<ProductEntity>
@Query("SELECT * FROM products")
fun getAllAsArray(): Array<ProductEntity>
@Query("SELECT * FROM products WHERE name = :name")
fun getProductsWithName(name: String): List<ProductEntity>
@Query("SELECT * FROM products WHERE name like :name OR description like :name")
fun searchProduct(term: String): List<ProductEntity>
@Query("SELECT * FROM products WHERE name in (:names)")
fun getProductsByName(names: List<String>): List<ProductEntity>
@Query("SELECT * FROM products WHERE qty >= :minQty AND qty <= :maxQty")
fun getProductsWithinInventory(minQty: Int, maxQty: Int): List<ProductEntity>
}
Query
@Dao
interface ProductsDao {
@Query("Select * from products")
fun getAllAsList(): List<ProductEntity>
@Query("SELECT * FROM products")
fun getAllAsArray(): Array<ProductEntity>
@Query("SELECT * FROM products WHERE name = :name")
fun getProductsWithName(name: String): List<ProductEntity>
@Query("SELECT * FROM products WHERE name like :name OR description like :name")
fun searchProduct(term: String): List<ProductEntity>
@Query("SELECT * FROM products WHERE name in (:names)")
fun getProductsByName(names: List<String>): List<ProductEntity>
@Query("SELECT * FROM products WHERE qty >= :minQty AND qty <= :maxQty")
fun getProductsWithinInventory(minQty: Int, maxQty: Int): List<ProductEntity>
}
Query
@Dao
interface ProductsDao {
@Query("Select * from products")
fun getAllAsList(): List<ProductEntity>
@Query("SELECT * FROM products")
fun getAllAsArray(): Array<ProductEntity>
@Query("SELECT * FROM products WHERE name = :name")
fun getProductsWithName(name: String): List<ProductEntity>
@Query("SELECT * FROM products WHERE name like :name OR description like :name")
fun searchProduct(term: String): List<ProductEntity>
@Query("SELECT * FROM products WHERE name in (:names)")
fun getProductsByName(names: List<String>): List<ProductEntity>
@Query("SELECT * FROM products WHERE qty >= :minQty AND qty <= :maxQty")
fun getProductsWithinInventory(minQty: Int, maxQty: Int): List<ProductEntity>
}
Query
@Dao
interface ProductsDao {
@Query("Select * from products")
fun getAllAsList(): List<ProductEntity>
@Query("SELECT * FROM products")
fun getAllAsArray(): Array<ProductEntity>
@Query("SELECT * FROM products WHERE name = :name")
fun getProductsWithName(name: String): List<ProductEntity>
@Query("SELECT * FROM products WHERE name like :name OR description like :name")
fun searchProduct(term: String): List<ProductEntity>
@Query("SELECT * FROM products WHERE name in (:names)")
fun getProductsByName(names: List<String>): List<ProductEntity>
@Query("SELECT * FROM products WHERE qty >= :minQty AND qty <= :maxQty")
fun getProductsWithinInventory(minQty: Int, maxQty: Int): List<ProductEntity>
}
Query
@Dao
interface ProductsDao {
@Query("Select * from products")
fun getAllAsList(): List<ProductEntity>
@Query("SELECT * FROM products")
fun getAllAsArray(): Array<ProductEntity>
@Query("SELECT * FROM products WHERE name = :name")
fun getProductsWithName(name: String): List<ProductEntity>
@Query("SELECT * FROM products WHERE name like :name OR description like :name")
fun searchProduct(term: String): List<ProductEntity>
@Query("SELECT * FROM products WHERE name in (:names)")
fun getProductsByName(names: List<String>): List<ProductEntity>
@Query("SELECT * FROM products WHERE qty >= :minQty AND qty <= :maxQty")
fun getProductsWithinInventory(minQty: Int, maxQty: Int): List<ProductEntity>
}
Query
@Dao
interface ProductsDao {
@Query("Select * from products")
fun getAllAsList(): List<ProductEntity>
@Query("SELECT * FROM products")
fun getAllAsArray(): Array<ProductEntity>
@Query("SELECT * FROM products WHERE name = :name")
fun getProductsWithName(name: String): List<ProductEntity>
@Query("SELECT * FROM products WHERE name like :name OR description like :name")
fun searchProduct(term: String): List<ProductEntity>
@Query("SELECT * FROM products WHERE name in (:names)")
fun getProductsByName(names: List<String>): List<ProductEntity>
@Query("SELECT * FROM products WHERE qty >= :minQty AND qty <= :maxQty")
fun getProductsWithinInventory(minQty: Int, maxQty: Int): List<ProductEntity>
}
Query
@Dao
interface ProductsDao {
@Query("Select * from products")
fun getAllAsList(): List<ProductEntity>
@Query("SELECT * FROM products")
fun getAllAsArray(): Array<ProductEntity>
@Query("SELECT * FROM products WHERE name = :name")
fun getProductsWithName(name: String): List<ProductEntity>
@Query("SELECT * FROM products WHERE name like :name OR description like :name")
fun searchProduct(term: String): List<ProductEntity>
@Query("SELECT * FROM products WHERE name in (:names)")
fun getProductsByName(names: List<String>): List<ProductEntity>
@Query("SELECT * FROM products WHERE qty >= :minQty AND qty <= :maxQty")
fun getProductsWithinInventory(minQty: Int, maxQty: Int): List<ProductEntity>
}
Query
@Dao
interface ProductsDao {
@Query("SELECT * FROM products WHERE id = :id")
fun getProducts(id: Long): ProductEntity
@Query("SELECT COUNT(*) FROM products")
fun getProductsCount(): Int
@Query("SELECT COUNT(*) AS count, name FROM products GROUP BY name")
fun getProductsCountByName(): List<ProductCountEntity>
}
class ProductCountEntity(
@ColumnInfo(name = "name") var name: String,
@ColumnInfo(name = "count") var count: Int
)
Query
@Dao
interface ProductsDao {
@Query("SELECT * FROM products WHERE id = :id")
fun getProducts(id: Long): ProductEntity
@Query("SELECT COUNT(*) FROM products")
fun getProductsCount(): Int
@Query("SELECT COUNT(*) AS count, name FROM products GROUP BY name")
fun getProductsCountByName(): List<ProductCountEntity>
}
class ProductCountEntity(
@ColumnInfo(name = "name") var name: String,
@ColumnInfo(name = "count") var count: Int
)
Query
@Dao
interface ProductsDao {
@Query("SELECT * FROM products WHERE id = :id")
fun getProducts(id: Long): ProductEntity
@Query("SELECT COUNT(*) FROM products")
fun getProductsCount(): Int
@Query("SELECT COUNT(*) AS count, name FROM products GROUP BY name")
fun getProductsCountByName(): List<ProductCountEntity>
}
class ProductCountEntity(
@ColumnInfo(name = "name") var name: String,
@ColumnInfo(name = "count") var count: Int
)
Query
@Dao
interface ProductsDao {
@Query("SELECT * FROM products WHERE id = :id")
fun getProducts(id: Long): ProductEntity
@Query("SELECT COUNT(*) FROM products")
fun getProductsCount(): Int
@Query("SELECT COUNT(*) AS count, name FROM products GROUP BY name")
fun getProductsCountByName(): List<ProductCountEntity>
}
class ProductCountEntity(
@ColumnInfo(name = "name") var name: String,
@ColumnInfo(name = "count") var count: Int
)
Database
Database
@Database(
entities = arrayOf(
ProductEntity::class,
InventoryEntity::class
),
version = 1
)
abstract class MyDatabase : RoomDatabase() {
abstract fun productsDao(): ProductsDao
abstract fun inventoryDao(): InventoryDao
}
Database
@Database(
entities = arrayOf(
ProductEntity::class,
InventoryEntity::class
),
version = 1
)
abstract class MyDatabase : RoomDatabase() {
abstract fun productsDao(): ProductsDao
abstract fun inventoryDao(): InventoryDao
}
Database
@Database(
entities = arrayOf(
ProductEntity::class,
InventoryEntity::class
),
version = 1
)
abstract class MyDatabase : RoomDatabase() {
abstract fun productsDao(): ProductsDao
abstract fun inventoryDao(): InventoryDao
}
Database
@Database(
entities = arrayOf(
ProductEntity::class,
InventoryEntity::class
),
version = 1
)
abstract class MyDatabase : RoomDatabase() {
abstract fun productsDao(): ProductsDao
abstract fun inventoryDao(): InventoryDao
}
Using database
val database: MyDatabase = Room
.databaseBuilder(applicationContext, MyDatabase::class.java, "database")
.build()
val products = database.productsDao().getAllAsList()
Using database
val database: MyDatabase = Room
.databaseBuilder(applicationContext, MyDatabase::class.java, "database")
.build()
val products = database.productsDao().getAllAsList()
Using database
val database: MyDatabase = Room
.databaseBuilder(applicationContext, MyDatabase::class.java, "database")
.build()
val products = database.productsDao().getAllAsList()
Use a single instance of
database!
Type Converters
Date (Boo)
vs.
Three-ten-abp (Yaay!)
Type converters
class DateTimeConverter {
private val df : DateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME
@TypeConverter
fun toTimestamp(dateTime: LocalDateTime) : String {
return dateTime.format(df)
}
@TypeConverter
fun toDateTime(timestamp:String) : LocalDateTime {
return LocalDateTime.parse(timestamp, df);
}
}
Type converters
class DateTimeConverter {
private val df : DateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME
@TypeConverter
fun toTimestamp(dateTime: LocalDateTime) : String {
return dateTime.format(df)
}
@TypeConverter
fun toDateTime(timestamp:String) : LocalDateTime {
return LocalDateTime.parse(timestamp, df);
}
}
Type converters
@Database(entities = arrayOf(ProductEntity::class), version = 1)
@TypeConverters(DateTimeConverter::class)
abstract class MyDatabase : RoomDatabase() {
abstract fun productsDao(): ProductsDao
}
Type converters
@Dao
@TypeConverters(DateTimeConverter::class)
interface InventoryDao {
@Query("Select * from inventory where date = :date")
fun getByDate(date: LocalDateTime)
@Query("Select * from inventory where date = :date")
fun getByDate2(date: LocalDateTime)
}
Type converters
@Dao
interface InventoryDao {
@Query("Select * from inventory where date = :date")
@TypeConverters(DateTimeConverter::class)
fun getByDate(date: LocalDateTime)
@Query("Select * from inventory where date = :date")
fun getByDate2(date: LocalDateTime)
}
Type converters
@Dao
interface InventoryDao {
@Query("Select * from inventory where date = :date")
fun getByDate(date: LocalDateTime)
@Query("Select * from inventory where date = :date")
fun getByDate2(@TypeConverters(DateTimeConverter::class) date: LocalDateTime)
}
Type converters
@Entity(tableName = "products")
class ProductEntity(
@PrimaryKey() @ColumnInfo(name = "id") var id: Long,
@ColumnInfo(name = "name") var name: String,
@ColumnInfo(name = "description") var description: String,
@ColumnInfo(name = "qty") var quantity: Long,
@ColumnInfo(name = "purchase_date") var purchaseDate: LocalDateTime
)
Type converters
@Entity(tableName = "products")
@TypeConverters(DateTimeConverter::class)
class ProductEntity(
@PrimaryKey() @ColumnInfo(name = "id") var id: Long,
@ColumnInfo(name = "name") var name: String,
@ColumnInfo(name = "description") var description: String,
@ColumnInfo(name = "qty") var quantity: Long,
@ColumnInfo(name = "purchase_date") var purchaseDate: LocalDateTime
)
Type converters
@Entity(tableName = "products")
class ProductEntity(
@PrimaryKey() @ColumnInfo(name = "id") var id: Long,
@ColumnInfo(name = "name") var name: String,
@ColumnInfo(name = "description") var description: String,
@ColumnInfo(name = "qty") var quantity: Long,
@TypeConverters(DateTimeConverter::class)
@ColumnInfo(name = "purchase_date") var purchaseDate: LocalDateTime
)
Migrations
val migrationFrom1To2 = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE products ADD COLUMN prices INTEGER")
}
}
val migrationFrom2To3 = object : Migration(2, 3) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE products ADD COLUMN color TEXT")
}
}
val database: MyDatabase = Room
.databaseBuilder(applicationContext, MyDatabase::class.java, "database")
.addMigrations(migrationFrom1To2, migrationFrom2To3)
.build()
Migrations
val migrationFrom1To2 = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE products ADD COLUMN prices INTEGER")
}
}
val migrationFrom2To3 = object : Migration(2, 3) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE products ADD COLUMN color TEXT")
}
}
val database: MyDatabase = Room
.databaseBuilder(applicationContext, MyDatabase::class.java, "database")
.addMigrations(migrationFrom1To2, migrationFrom2To3)
.build()
Migrations
val migrationFrom1To2 = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE products ADD COLUMN prices INTEGER")
}
}
val migrationFrom2To3 = object : Migration(2, 3) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE products ADD COLUMN color TEXT")
}
}
val database: MyDatabase = Room
.databaseBuilder(applicationContext, MyDatabase::class.java, "database")
.addMigrations(migrationFrom1To2, migrationFrom2To3)
.build()
Migrations
val migrationFrom1To2 = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE products ADD COLUMN prices INTEGER")
}
}
val migrationFrom2To3 = object : Migration(2, 3) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE products ADD COLUMN color TEXT")
}
}
val database: MyDatabase = Room
.databaseBuilder(applicationContext, MyDatabase::class.java, "database")
.addMigrations(migrationFrom1To2, migrationFrom2To3)
.build()
Migrations
@Database(entities = arrayOf(ProductEntity::class), version = 3)
@TypeConverters(DateTimeConverter::class)
abstract class MyDatabase : RoomDatabase() {
abstract fun productsDao(): ProductsDao
}
Warning!
If no migration is provided,
Room will rebuilt database
based on schema
LiveData
@Query("Select * from products")
fun getAllAsList(): LiveData<List<ProductEntity>>
RxJava 2
def room = '1.0.0-beta2'
implementation "android.arch.persistence.room:runtime:${room}"
kapt "android.arch.persistence.room:compiler:${room}"
implementation "android.arch.persistence.room:rxjava2:${room}"
RxJava 2
@Query("Select * from products")
fun getAllAsList(): Flowable<List<ProductEntity>>
@Query("SELECT * FROM products WHERE id = :id")
fun getProductById(id: Long): Single<ProductEntity>
@Query("SELECT * FROM products WHERE name = :name")
fun getProductByName(name: String): Maybe<ProductEntity>
RxJava 2
Flowable Maybe Single
No data - Just onComplete onError
Data onNext onSuccess onSuccess
Update onNext - -
Moar things!
But enough for today
Questions?
Database handling with room

More Related Content

What's hot

Commonality and Variability Analysis: Avoiding Duplicate Code
Commonality and Variability Analysis: Avoiding Duplicate CodeCommonality and Variability Analysis: Avoiding Duplicate Code
Commonality and Variability Analysis: Avoiding Duplicate Code
Alistair McKinnell
 
Oracle business intelligence publisher – developer training
Oracle business intelligence publisher – developer trainingOracle business intelligence publisher – developer training
Oracle business intelligence publisher – developer training
itprofessionals network
 
Airline reservation project using JAVA in NetBeans IDE
Airline reservation project using JAVA in NetBeans IDEAirline reservation project using JAVA in NetBeans IDE
Airline reservation project using JAVA in NetBeans IDE
HimanshiSingh71
 
Rmarkdown cheatsheet-2.0
Rmarkdown cheatsheet-2.0Rmarkdown cheatsheet-2.0
Rmarkdown cheatsheet-2.0
Dieudonne Nahigombeye
 
The Ring programming language version 1.9 book - Part 54 of 210
The Ring programming language version 1.9 book - Part 54 of 210The Ring programming language version 1.9 book - Part 54 of 210
The Ring programming language version 1.9 book - Part 54 of 210
Mahmoud Samir Fayed
 
Exploring ZIO Prelude: The game changer for typeclasses in Scala
Exploring ZIO Prelude: The game changer for typeclasses in ScalaExploring ZIO Prelude: The game changer for typeclasses in Scala
Exploring ZIO Prelude: The game changer for typeclasses in Scala
Jorge Vásquez
 
Moving to hybrid relational/JSON data models
Moving to hybrid relational/JSON data modelsMoving to hybrid relational/JSON data models
Moving to hybrid relational/JSON data models
MariaDB plc
 
NOSQL part of the SpringOne 2GX 2010 keynote
NOSQL part of the SpringOne 2GX 2010 keynoteNOSQL part of the SpringOne 2GX 2010 keynote
NOSQL part of the SpringOne 2GX 2010 keynote
Emil Eifrem
 
11. session 11 functions and objects
11. session 11   functions and objects11. session 11   functions and objects
11. session 11 functions and objects
Phúc Đỗ
 
Prototype Framework
Prototype FrameworkPrototype Framework
Prototype Framework
Julie Iskander
 
Parameterization is nothing but giving multiple input
Parameterization is nothing but giving multiple inputParameterization is nothing but giving multiple input
Parameterization is nothing but giving multiple input
uanna
 
Elementary Sort
Elementary SortElementary Sort
Elementary Sort
Sri Prasanna
 
From java to kotlin beyond alt+shift+cmd+k - Droidcon italy
From java to kotlin beyond alt+shift+cmd+k - Droidcon italyFrom java to kotlin beyond alt+shift+cmd+k - Droidcon italy
From java to kotlin beyond alt+shift+cmd+k - Droidcon italy
Fabio Collini
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
Loïc Descotte
 
Intro to MongoDB and datamodeling
Intro to MongoDB and datamodeling Intro to MongoDB and datamodeling
Intro to MongoDB and datamodeling
rogerbodamer
 
Async code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night TurinAsync code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Fabio Collini
 
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf MilanFrom Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
Fabio Collini
 
Phactory
PhactoryPhactory
Phactory
chriskite
 
Software architecture2008 ejbql-quickref
Software architecture2008 ejbql-quickrefSoftware architecture2008 ejbql-quickref
Software architecture2008 ejbql-quickref
jaiverlh
 
Introduction to JQuery
Introduction to JQueryIntroduction to JQuery
Introduction to JQuery
Muhammad Afzal Qureshi
 

What's hot (20)

Commonality and Variability Analysis: Avoiding Duplicate Code
Commonality and Variability Analysis: Avoiding Duplicate CodeCommonality and Variability Analysis: Avoiding Duplicate Code
Commonality and Variability Analysis: Avoiding Duplicate Code
 
Oracle business intelligence publisher – developer training
Oracle business intelligence publisher – developer trainingOracle business intelligence publisher – developer training
Oracle business intelligence publisher – developer training
 
Airline reservation project using JAVA in NetBeans IDE
Airline reservation project using JAVA in NetBeans IDEAirline reservation project using JAVA in NetBeans IDE
Airline reservation project using JAVA in NetBeans IDE
 
Rmarkdown cheatsheet-2.0
Rmarkdown cheatsheet-2.0Rmarkdown cheatsheet-2.0
Rmarkdown cheatsheet-2.0
 
The Ring programming language version 1.9 book - Part 54 of 210
The Ring programming language version 1.9 book - Part 54 of 210The Ring programming language version 1.9 book - Part 54 of 210
The Ring programming language version 1.9 book - Part 54 of 210
 
Exploring ZIO Prelude: The game changer for typeclasses in Scala
Exploring ZIO Prelude: The game changer for typeclasses in ScalaExploring ZIO Prelude: The game changer for typeclasses in Scala
Exploring ZIO Prelude: The game changer for typeclasses in Scala
 
Moving to hybrid relational/JSON data models
Moving to hybrid relational/JSON data modelsMoving to hybrid relational/JSON data models
Moving to hybrid relational/JSON data models
 
NOSQL part of the SpringOne 2GX 2010 keynote
NOSQL part of the SpringOne 2GX 2010 keynoteNOSQL part of the SpringOne 2GX 2010 keynote
NOSQL part of the SpringOne 2GX 2010 keynote
 
11. session 11 functions and objects
11. session 11   functions and objects11. session 11   functions and objects
11. session 11 functions and objects
 
Prototype Framework
Prototype FrameworkPrototype Framework
Prototype Framework
 
Parameterization is nothing but giving multiple input
Parameterization is nothing but giving multiple inputParameterization is nothing but giving multiple input
Parameterization is nothing but giving multiple input
 
Elementary Sort
Elementary SortElementary Sort
Elementary Sort
 
From java to kotlin beyond alt+shift+cmd+k - Droidcon italy
From java to kotlin beyond alt+shift+cmd+k - Droidcon italyFrom java to kotlin beyond alt+shift+cmd+k - Droidcon italy
From java to kotlin beyond alt+shift+cmd+k - Droidcon italy
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 
Intro to MongoDB and datamodeling
Intro to MongoDB and datamodeling Intro to MongoDB and datamodeling
Intro to MongoDB and datamodeling
 
Async code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night TurinAsync code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night Turin
 
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf MilanFrom Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
 
Phactory
PhactoryPhactory
Phactory
 
Software architecture2008 ejbql-quickref
Software architecture2008 ejbql-quickrefSoftware architecture2008 ejbql-quickref
Software architecture2008 ejbql-quickref
 
Introduction to JQuery
Introduction to JQueryIntroduction to JQuery
Introduction to JQuery
 

Similar to Database handling with room

Persisting Data on SQLite using Room
Persisting Data on SQLite using RoomPersisting Data on SQLite using Room
Persisting Data on SQLite using Room
Nelson Glauber Leal
 
Java Persistence API
Java Persistence APIJava Persistence API
Java Persistence API
Carol McDonald
 
Micro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateMicro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicate
Kiev ALT.NET
 
Wicket KT part 2
Wicket KT part 2Wicket KT part 2
Wicket KT part 2
stuq
 
Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012
Anton Arhipov
 
Minha api deve ser rest?
Minha api deve ser rest?Minha api deve ser rest?
Minha api deve ser rest?
Everton Tavares
 
Implementation of EAV pattern for ActiveRecord models
Implementation of EAV pattern for ActiveRecord modelsImplementation of EAV pattern for ActiveRecord models
Implementation of EAV pattern for ActiveRecord models
Kostyantyn Stepanyuk
 
jQuery Essentials
jQuery EssentialsjQuery Essentials
jQuery Essentials
Marc Grabanski
 
EclipseCon2011 Cross-Platform Mobile Development with Eclipse
EclipseCon2011 Cross-Platform Mobile Development with EclipseEclipseCon2011 Cross-Platform Mobile Development with Eclipse
EclipseCon2011 Cross-Platform Mobile Development with Eclipse
Heiko Behrens
 
Paintfree Object-Document Mapping for MongoDB by Philipp Krenn
Paintfree Object-Document Mapping for MongoDB by Philipp KrennPaintfree Object-Document Mapping for MongoDB by Philipp Krenn
Paintfree Object-Document Mapping for MongoDB by Philipp Krenn
JavaDayUA
 
Creating a Facebook Clone - Part XXXI - Transcript.pdf
Creating a Facebook Clone - Part XXXI - Transcript.pdfCreating a Facebook Clone - Part XXXI - Transcript.pdf
Creating a Facebook Clone - Part XXXI - Transcript.pdf
ShaiAlmog1
 
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin WayTDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
tdc-globalcode
 
Improving Correctness with Types Kats Conf
Improving Correctness with Types Kats ConfImproving Correctness with Types Kats Conf
Improving Correctness with Types Kats Conf
Iain Hull
 
Getting the most out of Java [Nordic Coding-2010]
Getting the most out of Java [Nordic Coding-2010]Getting the most out of Java [Nordic Coding-2010]
Getting the most out of Java [Nordic Coding-2010]
Sven Efftinge
 
First few months with Kotlin - Introduction through android examples
First few months with Kotlin - Introduction through android examplesFirst few months with Kotlin - Introduction through android examples
First few months with Kotlin - Introduction through android examples
Nebojša Vukšić
 
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docx
1  MVC – Ajax and Modal Views AJAX stands for Asynch.docx1  MVC – Ajax and Modal Views AJAX stands for Asynch.docx
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docx
honey725342
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기
Arawn Park
 
Reactive clean architecture
Reactive clean architectureReactive clean architecture
Reactive clean architecture
Viktor Nyblom
 
Getting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NETGetting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NET
Tomas Jansson
 
Working With JQuery Part1
Working With JQuery Part1Working With JQuery Part1
Working With JQuery Part1
saydin_soft
 

Similar to Database handling with room (20)

Persisting Data on SQLite using Room
Persisting Data on SQLite using RoomPersisting Data on SQLite using Room
Persisting Data on SQLite using Room
 
Java Persistence API
Java Persistence APIJava Persistence API
Java Persistence API
 
Micro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateMicro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicate
 
Wicket KT part 2
Wicket KT part 2Wicket KT part 2
Wicket KT part 2
 
Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012
 
Minha api deve ser rest?
Minha api deve ser rest?Minha api deve ser rest?
Minha api deve ser rest?
 
Implementation of EAV pattern for ActiveRecord models
Implementation of EAV pattern for ActiveRecord modelsImplementation of EAV pattern for ActiveRecord models
Implementation of EAV pattern for ActiveRecord models
 
jQuery Essentials
jQuery EssentialsjQuery Essentials
jQuery Essentials
 
EclipseCon2011 Cross-Platform Mobile Development with Eclipse
EclipseCon2011 Cross-Platform Mobile Development with EclipseEclipseCon2011 Cross-Platform Mobile Development with Eclipse
EclipseCon2011 Cross-Platform Mobile Development with Eclipse
 
Paintfree Object-Document Mapping for MongoDB by Philipp Krenn
Paintfree Object-Document Mapping for MongoDB by Philipp KrennPaintfree Object-Document Mapping for MongoDB by Philipp Krenn
Paintfree Object-Document Mapping for MongoDB by Philipp Krenn
 
Creating a Facebook Clone - Part XXXI - Transcript.pdf
Creating a Facebook Clone - Part XXXI - Transcript.pdfCreating a Facebook Clone - Part XXXI - Transcript.pdf
Creating a Facebook Clone - Part XXXI - Transcript.pdf
 
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin WayTDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
 
Improving Correctness with Types Kats Conf
Improving Correctness with Types Kats ConfImproving Correctness with Types Kats Conf
Improving Correctness with Types Kats Conf
 
Getting the most out of Java [Nordic Coding-2010]
Getting the most out of Java [Nordic Coding-2010]Getting the most out of Java [Nordic Coding-2010]
Getting the most out of Java [Nordic Coding-2010]
 
First few months with Kotlin - Introduction through android examples
First few months with Kotlin - Introduction through android examplesFirst few months with Kotlin - Introduction through android examples
First few months with Kotlin - Introduction through android examples
 
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docx
1  MVC – Ajax and Modal Views AJAX stands for Asynch.docx1  MVC – Ajax and Modal Views AJAX stands for Asynch.docx
1 MVC – Ajax and Modal Views AJAX stands for Asynch.docx
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기
 
Reactive clean architecture
Reactive clean architectureReactive clean architecture
Reactive clean architecture
 
Getting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NETGetting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NET
 
Working With JQuery Part1
Working With JQuery Part1Working With JQuery Part1
Working With JQuery Part1
 

More from Sergi Martínez

Kotlin, a modern language for modern times
Kotlin, a modern language for modern timesKotlin, a modern language for modern times
Kotlin, a modern language for modern times
Sergi Martínez
 
What is flutter and why should i care?
What is flutter and why should i care?What is flutter and why should i care?
What is flutter and why should i care?
Sergi Martínez
 
What is flutter and why should i care? Lightning talk
What is flutter and why should i care? Lightning talkWhat is flutter and why should i care? Lightning talk
What is flutter and why should i care? Lightning talk
Sergi Martínez
 
Let’s talk about star wars with Dialog Flow
Let’s talk about star wars with Dialog FlowLet’s talk about star wars with Dialog Flow
Let’s talk about star wars with Dialog Flow
Sergi Martínez
 
Realm or: How I learned to stop worrying and love my app database
Realm or: How I learned to stop worrying and love my app databaseRealm or: How I learned to stop worrying and love my app database
Realm or: How I learned to stop worrying and love my app database
Sergi Martínez
 
Android data binding
Android data bindingAndroid data binding
Android data binding
Sergi Martínez
 
It's the arts! Playing around with the Android canvas
It's the arts! Playing around with the Android canvasIt's the arts! Playing around with the Android canvas
It's the arts! Playing around with the Android canvas
Sergi Martínez
 
Introduction to Android Fragments
Introduction to Android FragmentsIntroduction to Android Fragments
Introduction to Android Fragments
Sergi Martínez
 
Android master class
Android master classAndroid master class
Android master class
Sergi Martínez
 
Creating multillingual apps for android
Creating multillingual apps for androidCreating multillingual apps for android
Creating multillingual apps for android
Sergi Martínez
 
Píldoras android i. Intro - 2ª parte
Píldoras android i. Intro - 2ª partePíldoras android i. Intro - 2ª parte
Píldoras android i. Intro - 2ª parte
Sergi Martínez
 
Introducción a mobclix
Introducción a mobclixIntroducción a mobclix
Introducción a mobclix
Sergi Martínez
 
Admob y yo
Admob y yoAdmob y yo
Admob y yo
Sergi Martínez
 

More from Sergi Martínez (14)

Kotlin, a modern language for modern times
Kotlin, a modern language for modern timesKotlin, a modern language for modern times
Kotlin, a modern language for modern times
 
What is flutter and why should i care?
What is flutter and why should i care?What is flutter and why should i care?
What is flutter and why should i care?
 
What is flutter and why should i care? Lightning talk
What is flutter and why should i care? Lightning talkWhat is flutter and why should i care? Lightning talk
What is flutter and why should i care? Lightning talk
 
Let’s talk about star wars with Dialog Flow
Let’s talk about star wars with Dialog FlowLet’s talk about star wars with Dialog Flow
Let’s talk about star wars with Dialog Flow
 
Realm or: How I learned to stop worrying and love my app database
Realm or: How I learned to stop worrying and love my app databaseRealm or: How I learned to stop worrying and love my app database
Realm or: How I learned to stop worrying and love my app database
 
Android data binding
Android data bindingAndroid data binding
Android data binding
 
It's the arts! Playing around with the Android canvas
It's the arts! Playing around with the Android canvasIt's the arts! Playing around with the Android canvas
It's the arts! Playing around with the Android canvas
 
Smartphones
SmartphonesSmartphones
Smartphones
 
Introduction to Android Fragments
Introduction to Android FragmentsIntroduction to Android Fragments
Introduction to Android Fragments
 
Android master class
Android master classAndroid master class
Android master class
 
Creating multillingual apps for android
Creating multillingual apps for androidCreating multillingual apps for android
Creating multillingual apps for android
 
Píldoras android i. Intro - 2ª parte
Píldoras android i. Intro - 2ª partePíldoras android i. Intro - 2ª parte
Píldoras android i. Intro - 2ª parte
 
Introducción a mobclix
Introducción a mobclixIntroducción a mobclix
Introducción a mobclix
 
Admob y yo
Admob y yoAdmob y yo
Admob y yo
 

Recently uploaded

June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Principle of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptxPrinciple of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptx
BibashShahi
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
Edge AI and Vision Alliance
 
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Pitangent Analytics & Technology Solutions Pvt. Ltd
 
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframeDigital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Precisely
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
Leveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and StandardsLeveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and Standards
Neo4j
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
Alex Pruden
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
MichaelKnudsen27
 
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
saastr
 
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
Edge AI and Vision Alliance
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
Hiroshi SHIBATA
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
c5vrf27qcz
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Neo4j
 
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge GraphGraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
Neo4j
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
Jason Yip
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
ScyllaDB
 
Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
Antonios Katsarakis
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Alpen-Adria-Universität
 

Recently uploaded (20)

June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
 
Principle of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptxPrinciple of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptx
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
 
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
Crafting Excellence: A Comprehensive Guide to iOS Mobile App Development Serv...
 
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframeDigital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
Leveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and StandardsLeveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and Standards
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
 
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
 
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
 
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge GraphGraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
 
Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
 

Database handling with room

  • 5. A library to handle android databases via an abstraction layer
  • 11. Before anything else repositories { jcenter() maven { url 'https://maven.google.com' } } def room = '1.0.0-beta2' implementation "android.arch.persistence.room:runtime:${room}" kapt "android.arch.persistence.room:compiler:${room}"
  • 13. Simple entity @Entity(tableName = "products") class ProductEntity( @PrimaryKey() @ColumnInfo(name = "id") var id: Long, @ColumnInfo(name = "name") var name: String, @ColumnInfo(name = "description") var description: String, @ColumnInfo(name = "qty") var quantity: Long )
  • 14. Simple entity @Entity(tableName = "products") class ProductEntity( @PrimaryKey() @ColumnInfo(name = "id") var id: Long, @ColumnInfo(name = "name") var name: String, @ColumnInfo(name = "description") var description: String, @ColumnInfo(name = "qty") var quantity: Long )
  • 15. Simple entity @Entity(tableName = "products") class ProductEntity( @PrimaryKey() @ColumnInfo(name = "id") var id: Long, @ColumnInfo(name = "name") var name: String, @ColumnInfo(name = "description") var description: String, @ColumnInfo(name = "qty") var quantity: Long )
  • 16. Simple entity @Entity(tableName = "products") class ProductEntity( @PrimaryKey() @ColumnInfo(name = "id") var id: Long, @ColumnInfo(name = "name") var name: String, @ColumnInfo(name = "description") var description: String, @ColumnInfo(name = "qty") var quantity: Long )
  • 17. Indexes @Entity(tableName = "inventory", indices = arrayOf(Index("provider_id", "product_id", unique = true))) class InventoryEntity( @PrimaryKey() var id: Long, @ColumnInfo(name = "provider_id") var providerId: Long, @ColumnInfo(name = "product_id") var productId: Long, @ColumnInfo(name = "qty") var quantity: Long )
  • 18. Composed PK @Entity(tableName = "inventory", primaryKeys = arrayOf("provider_id", "product_id")) class InventoryEntity( @ColumnInfo(name = "provider_id") var providerId: Long, @ColumnInfo(name = "product_id") var productId: Long, @ColumnInfo(name = "qty") var quantity: Long )
  • 19. Foreign keys @Entity( tableName = "inventory", foreignKeys = arrayOf( ForeignKey( entity = ProductEntity::class, parentColumns = arrayOf("id"), childColumns = arrayOf("product_id") ) ) ) class InventoryEntity( @PrimaryKey() var id: Long, @ColumnInfo(name = "provider_id") var providerId: Long, @ColumnInfo(name = "product_id") var productId: Long, @ColumnInfo(name = "qty") var quantity: Long )
  • 20. Foreign keys @Entity( tableName = "inventory", foreignKeys = arrayOf( ForeignKey( entity = ProductEntity::class, parentColumns = arrayOf("id"), childColumns = arrayOf("product_id") ) ) ) class InventoryEntity( @PrimaryKey() var id: Long, @ColumnInfo(name = "provider_id") var providerId: Long, @ColumnInfo(name = "product_id") var productId: Long, @ColumnInfo(name = "qty") var quantity: Long )
  • 21. Foreign keys @Entity( tableName = "inventory", foreignKeys = arrayOf( ForeignKey( entity = ProductEntity::class, parentColumns = arrayOf("id"), childColumns = arrayOf("product_id") ) ) ) class InventoryEntity( @PrimaryKey() var id: Long, @ColumnInfo(name = "provider_id") var providerId: Long, @ColumnInfo(name = "product_id") var productId: Long, @ColumnInfo(name = "qty") var quantity: Long )
  • 22. Foreign keys @Entity( tableName = "inventory", foreignKeys = arrayOf( ForeignKey( entity = ProductEntity::class, parentColumns = arrayOf("id"), childColumns = arrayOf("product_id") ) ) ) class InventoryEntity( @PrimaryKey() var id: Long, @ColumnInfo(name = "provider_id") var providerId: Long, @ColumnInfo(name = "product_id") var productId: Long, @ColumnInfo(name = "qty") var quantity: Long )
  • 23. Foreign keys @Entity( tableName = "inventory", foreignKeys = arrayOf( ForeignKey( entity = ProductEntity::class, parentColumns = arrayOf("id"), childColumns = arrayOf("product_id") ) ) ) class InventoryEntity( @PrimaryKey() var id: Long, @ColumnInfo(name = "provider_id") var providerId: Long, @ColumnInfo(name = "product_id") var productId: Long, @ColumnInfo(name = "qty") var quantity: Long )
  • 24. Foreign keys @Entity( tableName = "inventory", foreignKeys = arrayOf( ForeignKey( entity = ProductEntity::class, parentColumns = arrayOf("id"), childColumns = arrayOf("product_id") ) ) ) class InventoryEntity( @PrimaryKey() var id: Long, @ColumnInfo(name = "provider_id") var providerId: Long, @ColumnInfo(name = "product_id") var productId: Long, @ColumnInfo(name = "qty") var quantity: Long )
  • 25. Nested objects @Entity(tableName = "products") class ProductEntity( @PrimaryKey() @ColumnInfo(name = "id") var id: Long, @ColumnInfo(name = "name") var name: String, @ColumnInfo(name = "description") var description: String, @Embedded var info: ProductInfo ) class ProductInfo( @ColumnInfo(name = "color") var color: String, @ColumnInfo(name = "size") var size: String ) products id name description color size
  • 26. Nested objects @Entity(tableName = "products") class ProductEntity( @PrimaryKey() @ColumnInfo(name = "id") var id: Long, @ColumnInfo(name = "name") var name: String, @ColumnInfo(name = "description") var description: String, @Embedded var info: ProductInfo ) class ProductInfo( @ColumnInfo(name = "color") var color: String, @ColumnInfo(name = "size") var size: String ) products id name description color size
  • 27. Nested objects @Entity(tableName = "products") class ProductEntity( @PrimaryKey() @ColumnInfo(name = "id") var id: Long, @ColumnInfo(name = "name") var name: String, @ColumnInfo(name = "description") var description: String, @Embedded var info: ProductInfo ) class ProductInfo( @ColumnInfo(name = "color") var color: String, @ColumnInfo(name = "size") var size: String ) products id name description color size
  • 28. Nested objects @Entity(tableName = "products") class ProductEntity( @PrimaryKey() @ColumnInfo(name = "id") var id: Long, @ColumnInfo(name = "name") var name: String, @ColumnInfo(name = "description") var description: String, @Embedded var info: ProductInfo ) class ProductInfo( @ColumnInfo(name = "color") var color: String, @ColumnInfo(name = "size") var size: String ) products id name description color size
  • 29. DAOs
  • 30. Simple DAO @Dao interface ProductsDao { @Insert(onConflict = REPLACE) fun insert(productEntity: ProductEntity): Long @Query("Select * from products") fun getAll(): List<ProductEntity> @Update fun update(productEntity: ProductEntity): Int @Delete fun delete(productEntity: ProductEntity): Int }
  • 31. Simple DAO @Dao interface ProductsDao { @Insert(onConflict = REPLACE) fun insert(productEntity: ProductEntity): Long @Query("Select * from products") fun getAll(): List<ProductEntity> @Update fun update(productEntity: ProductEntity): Int @Delete fun delete(productEntity: ProductEntity): Int }
  • 32. Simple DAO @Dao interface ProductsDao { @Insert(onConflict = REPLACE) fun insert(productEntity: ProductEntity): Long @Query("Select * from products") fun getAll(): List<ProductEntity> @Update fun update(productEntity: ProductEntity): Int @Delete fun delete(productEntity: ProductEntity): Int } Row id
  • 33. Simple DAO @Dao interface ProductsDao { @Insert(onConflict = REPLACE) fun insert(productEntity: ProductEntity): Long @Query("Select * from products") fun getAll(): List<ProductEntity> @Update fun update(productEntity: ProductEntity): Int @Delete fun delete(productEntity: ProductEntity): Int }
  • 34. Simple DAO @Dao interface ProductsDao { @Insert(onConflict = REPLACE) fun insert(productEntity: ProductEntity): Long @Query("Select * from products") fun getAll(): List<ProductEntity> @Update fun update(productEntity: ProductEntity): Int @Delete fun delete(productEntity: ProductEntity): Int } # Modified rows
  • 35. Simple DAO @Dao interface ProductsDao { @Insert(onConflict = REPLACE) fun insert(productEntity: ProductEntity): Long @Query("Select * from products") fun getAll(): List<ProductEntity> @Update fun update(productEntity: ProductEntity): Int @Delete fun delete(productEntity: ProductEntity): Int }
  • 36. Insert @Dao interface ProductsDao { @Insert(onConflict = REPLACE) fun insert(product: ProductEntity): Long @Insert(onConflict = REPLACE) fun insertAll(vararg products: ProductEntity) : List<Long> @Insert(onConflict = ROLLBACK) fun insertTwo(product: ProductEntity, otherProduct: ProductEntity): List<Long> @Insert(onConflict = ABORT) fun weirdInsert(product: ProductEntity, products: List<ProductEntity>): List<Long> }
  • 37. Update @Dao interface ProductsDao { @Update() fun update(product: ProductEntity): Int @Update() fun update(vararg users: ProductEntity): Int }
  • 38. Delete @Dao interface ProductsDao { @Delete() fun delete(product: ProductEntity): Int @Delete() fun delete(vararg users: ProductEntity): Int } Only primary key is matched
  • 39. Query @Dao interface ProductsDao { @Query("Select * from products") fun getAllAsList(): List<ProductEntity> @Query("SELECT * FROM products") fun getAllAsArray(): Array<ProductEntity> @Query("SELECT * FROM products WHERE name = :name") fun getProductsWithName(name: String): List<ProductEntity> @Query("SELECT * FROM products WHERE name like :name OR description like :name") fun searchProduct(term: String): List<ProductEntity> @Query("SELECT * FROM products WHERE name in (:names)") fun getProductsByName(names: List<String>): List<ProductEntity> @Query("SELECT * FROM products WHERE qty >= :minQty AND qty <= :maxQty") fun getProductsWithinInventory(minQty: Int, maxQty: Int): List<ProductEntity> }
  • 40. Query @Dao interface ProductsDao { @Query("Select * from products") fun getAllAsList(): List<ProductEntity> @Query("SELECT * FROM products") fun getAllAsArray(): Array<ProductEntity> @Query("SELECT * FROM products WHERE name = :name") fun getProductsWithName(name: String): List<ProductEntity> @Query("SELECT * FROM products WHERE name like :name OR description like :name") fun searchProduct(term: String): List<ProductEntity> @Query("SELECT * FROM products WHERE name in (:names)") fun getProductsByName(names: List<String>): List<ProductEntity> @Query("SELECT * FROM products WHERE qty >= :minQty AND qty <= :maxQty") fun getProductsWithinInventory(minQty: Int, maxQty: Int): List<ProductEntity> }
  • 41. Query @Dao interface ProductsDao { @Query("Select * from products") fun getAllAsList(): List<ProductEntity> @Query("SELECT * FROM products") fun getAllAsArray(): Array<ProductEntity> @Query("SELECT * FROM products WHERE name = :name") fun getProductsWithName(name: String): List<ProductEntity> @Query("SELECT * FROM products WHERE name like :name OR description like :name") fun searchProduct(term: String): List<ProductEntity> @Query("SELECT * FROM products WHERE name in (:names)") fun getProductsByName(names: List<String>): List<ProductEntity> @Query("SELECT * FROM products WHERE qty >= :minQty AND qty <= :maxQty") fun getProductsWithinInventory(minQty: Int, maxQty: Int): List<ProductEntity> }
  • 42. Query @Dao interface ProductsDao { @Query("Select * from products") fun getAllAsList(): List<ProductEntity> @Query("SELECT * FROM products") fun getAllAsArray(): Array<ProductEntity> @Query("SELECT * FROM products WHERE name = :name") fun getProductsWithName(name: String): List<ProductEntity> @Query("SELECT * FROM products WHERE name like :name OR description like :name") fun searchProduct(term: String): List<ProductEntity> @Query("SELECT * FROM products WHERE name in (:names)") fun getProductsByName(names: List<String>): List<ProductEntity> @Query("SELECT * FROM products WHERE qty >= :minQty AND qty <= :maxQty") fun getProductsWithinInventory(minQty: Int, maxQty: Int): List<ProductEntity> }
  • 43. Query @Dao interface ProductsDao { @Query("Select * from products") fun getAllAsList(): List<ProductEntity> @Query("SELECT * FROM products") fun getAllAsArray(): Array<ProductEntity> @Query("SELECT * FROM products WHERE name = :name") fun getProductsWithName(name: String): List<ProductEntity> @Query("SELECT * FROM products WHERE name like :name OR description like :name") fun searchProduct(term: String): List<ProductEntity> @Query("SELECT * FROM products WHERE name in (:names)") fun getProductsByName(names: List<String>): List<ProductEntity> @Query("SELECT * FROM products WHERE qty >= :minQty AND qty <= :maxQty") fun getProductsWithinInventory(minQty: Int, maxQty: Int): List<ProductEntity> }
  • 44. Query @Dao interface ProductsDao { @Query("Select * from products") fun getAllAsList(): List<ProductEntity> @Query("SELECT * FROM products") fun getAllAsArray(): Array<ProductEntity> @Query("SELECT * FROM products WHERE name = :name") fun getProductsWithName(name: String): List<ProductEntity> @Query("SELECT * FROM products WHERE name like :name OR description like :name") fun searchProduct(term: String): List<ProductEntity> @Query("SELECT * FROM products WHERE name in (:names)") fun getProductsByName(names: List<String>): List<ProductEntity> @Query("SELECT * FROM products WHERE qty >= :minQty AND qty <= :maxQty") fun getProductsWithinInventory(minQty: Int, maxQty: Int): List<ProductEntity> }
  • 45. Query @Dao interface ProductsDao { @Query("Select * from products") fun getAllAsList(): List<ProductEntity> @Query("SELECT * FROM products") fun getAllAsArray(): Array<ProductEntity> @Query("SELECT * FROM products WHERE name = :name") fun getProductsWithName(name: String): List<ProductEntity> @Query("SELECT * FROM products WHERE name like :name OR description like :name") fun searchProduct(term: String): List<ProductEntity> @Query("SELECT * FROM products WHERE name in (:names)") fun getProductsByName(names: List<String>): List<ProductEntity> @Query("SELECT * FROM products WHERE qty >= :minQty AND qty <= :maxQty") fun getProductsWithinInventory(minQty: Int, maxQty: Int): List<ProductEntity> }
  • 46. Query @Dao interface ProductsDao { @Query("SELECT * FROM products WHERE id = :id") fun getProducts(id: Long): ProductEntity @Query("SELECT COUNT(*) FROM products") fun getProductsCount(): Int @Query("SELECT COUNT(*) AS count, name FROM products GROUP BY name") fun getProductsCountByName(): List<ProductCountEntity> } class ProductCountEntity( @ColumnInfo(name = "name") var name: String, @ColumnInfo(name = "count") var count: Int )
  • 47. Query @Dao interface ProductsDao { @Query("SELECT * FROM products WHERE id = :id") fun getProducts(id: Long): ProductEntity @Query("SELECT COUNT(*) FROM products") fun getProductsCount(): Int @Query("SELECT COUNT(*) AS count, name FROM products GROUP BY name") fun getProductsCountByName(): List<ProductCountEntity> } class ProductCountEntity( @ColumnInfo(name = "name") var name: String, @ColumnInfo(name = "count") var count: Int )
  • 48. Query @Dao interface ProductsDao { @Query("SELECT * FROM products WHERE id = :id") fun getProducts(id: Long): ProductEntity @Query("SELECT COUNT(*) FROM products") fun getProductsCount(): Int @Query("SELECT COUNT(*) AS count, name FROM products GROUP BY name") fun getProductsCountByName(): List<ProductCountEntity> } class ProductCountEntity( @ColumnInfo(name = "name") var name: String, @ColumnInfo(name = "count") var count: Int )
  • 49. Query @Dao interface ProductsDao { @Query("SELECT * FROM products WHERE id = :id") fun getProducts(id: Long): ProductEntity @Query("SELECT COUNT(*) FROM products") fun getProductsCount(): Int @Query("SELECT COUNT(*) AS count, name FROM products GROUP BY name") fun getProductsCountByName(): List<ProductCountEntity> } class ProductCountEntity( @ColumnInfo(name = "name") var name: String, @ColumnInfo(name = "count") var count: Int )
  • 51. Database @Database( entities = arrayOf( ProductEntity::class, InventoryEntity::class ), version = 1 ) abstract class MyDatabase : RoomDatabase() { abstract fun productsDao(): ProductsDao abstract fun inventoryDao(): InventoryDao }
  • 52. Database @Database( entities = arrayOf( ProductEntity::class, InventoryEntity::class ), version = 1 ) abstract class MyDatabase : RoomDatabase() { abstract fun productsDao(): ProductsDao abstract fun inventoryDao(): InventoryDao }
  • 53. Database @Database( entities = arrayOf( ProductEntity::class, InventoryEntity::class ), version = 1 ) abstract class MyDatabase : RoomDatabase() { abstract fun productsDao(): ProductsDao abstract fun inventoryDao(): InventoryDao }
  • 54. Database @Database( entities = arrayOf( ProductEntity::class, InventoryEntity::class ), version = 1 ) abstract class MyDatabase : RoomDatabase() { abstract fun productsDao(): ProductsDao abstract fun inventoryDao(): InventoryDao }
  • 55. Using database val database: MyDatabase = Room .databaseBuilder(applicationContext, MyDatabase::class.java, "database") .build() val products = database.productsDao().getAllAsList()
  • 56. Using database val database: MyDatabase = Room .databaseBuilder(applicationContext, MyDatabase::class.java, "database") .build() val products = database.productsDao().getAllAsList()
  • 57. Using database val database: MyDatabase = Room .databaseBuilder(applicationContext, MyDatabase::class.java, "database") .build() val products = database.productsDao().getAllAsList()
  • 58. Use a single instance of database!
  • 61. Type converters class DateTimeConverter { private val df : DateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME @TypeConverter fun toTimestamp(dateTime: LocalDateTime) : String { return dateTime.format(df) } @TypeConverter fun toDateTime(timestamp:String) : LocalDateTime { return LocalDateTime.parse(timestamp, df); } }
  • 62. Type converters class DateTimeConverter { private val df : DateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME @TypeConverter fun toTimestamp(dateTime: LocalDateTime) : String { return dateTime.format(df) } @TypeConverter fun toDateTime(timestamp:String) : LocalDateTime { return LocalDateTime.parse(timestamp, df); } }
  • 63. Type converters @Database(entities = arrayOf(ProductEntity::class), version = 1) @TypeConverters(DateTimeConverter::class) abstract class MyDatabase : RoomDatabase() { abstract fun productsDao(): ProductsDao }
  • 64. Type converters @Dao @TypeConverters(DateTimeConverter::class) interface InventoryDao { @Query("Select * from inventory where date = :date") fun getByDate(date: LocalDateTime) @Query("Select * from inventory where date = :date") fun getByDate2(date: LocalDateTime) }
  • 65. Type converters @Dao interface InventoryDao { @Query("Select * from inventory where date = :date") @TypeConverters(DateTimeConverter::class) fun getByDate(date: LocalDateTime) @Query("Select * from inventory where date = :date") fun getByDate2(date: LocalDateTime) }
  • 66. Type converters @Dao interface InventoryDao { @Query("Select * from inventory where date = :date") fun getByDate(date: LocalDateTime) @Query("Select * from inventory where date = :date") fun getByDate2(@TypeConverters(DateTimeConverter::class) date: LocalDateTime) }
  • 67. Type converters @Entity(tableName = "products") class ProductEntity( @PrimaryKey() @ColumnInfo(name = "id") var id: Long, @ColumnInfo(name = "name") var name: String, @ColumnInfo(name = "description") var description: String, @ColumnInfo(name = "qty") var quantity: Long, @ColumnInfo(name = "purchase_date") var purchaseDate: LocalDateTime )
  • 68. Type converters @Entity(tableName = "products") @TypeConverters(DateTimeConverter::class) class ProductEntity( @PrimaryKey() @ColumnInfo(name = "id") var id: Long, @ColumnInfo(name = "name") var name: String, @ColumnInfo(name = "description") var description: String, @ColumnInfo(name = "qty") var quantity: Long, @ColumnInfo(name = "purchase_date") var purchaseDate: LocalDateTime )
  • 69. Type converters @Entity(tableName = "products") class ProductEntity( @PrimaryKey() @ColumnInfo(name = "id") var id: Long, @ColumnInfo(name = "name") var name: String, @ColumnInfo(name = "description") var description: String, @ColumnInfo(name = "qty") var quantity: Long, @TypeConverters(DateTimeConverter::class) @ColumnInfo(name = "purchase_date") var purchaseDate: LocalDateTime )
  • 70. Migrations val migrationFrom1To2 = object : Migration(1, 2) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("ALTER TABLE products ADD COLUMN prices INTEGER") } } val migrationFrom2To3 = object : Migration(2, 3) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("ALTER TABLE products ADD COLUMN color TEXT") } } val database: MyDatabase = Room .databaseBuilder(applicationContext, MyDatabase::class.java, "database") .addMigrations(migrationFrom1To2, migrationFrom2To3) .build()
  • 71. Migrations val migrationFrom1To2 = object : Migration(1, 2) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("ALTER TABLE products ADD COLUMN prices INTEGER") } } val migrationFrom2To3 = object : Migration(2, 3) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("ALTER TABLE products ADD COLUMN color TEXT") } } val database: MyDatabase = Room .databaseBuilder(applicationContext, MyDatabase::class.java, "database") .addMigrations(migrationFrom1To2, migrationFrom2To3) .build()
  • 72. Migrations val migrationFrom1To2 = object : Migration(1, 2) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("ALTER TABLE products ADD COLUMN prices INTEGER") } } val migrationFrom2To3 = object : Migration(2, 3) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("ALTER TABLE products ADD COLUMN color TEXT") } } val database: MyDatabase = Room .databaseBuilder(applicationContext, MyDatabase::class.java, "database") .addMigrations(migrationFrom1To2, migrationFrom2To3) .build()
  • 73. Migrations val migrationFrom1To2 = object : Migration(1, 2) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("ALTER TABLE products ADD COLUMN prices INTEGER") } } val migrationFrom2To3 = object : Migration(2, 3) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("ALTER TABLE products ADD COLUMN color TEXT") } } val database: MyDatabase = Room .databaseBuilder(applicationContext, MyDatabase::class.java, "database") .addMigrations(migrationFrom1To2, migrationFrom2To3) .build()
  • 74. Migrations @Database(entities = arrayOf(ProductEntity::class), version = 3) @TypeConverters(DateTimeConverter::class) abstract class MyDatabase : RoomDatabase() { abstract fun productsDao(): ProductsDao }
  • 75. Warning! If no migration is provided, Room will rebuilt database based on schema
  • 76. LiveData @Query("Select * from products") fun getAllAsList(): LiveData<List<ProductEntity>>
  • 77. RxJava 2 def room = '1.0.0-beta2' implementation "android.arch.persistence.room:runtime:${room}" kapt "android.arch.persistence.room:compiler:${room}" implementation "android.arch.persistence.room:rxjava2:${room}"
  • 78. RxJava 2 @Query("Select * from products") fun getAllAsList(): Flowable<List<ProductEntity>> @Query("SELECT * FROM products WHERE id = :id") fun getProductById(id: Long): Single<ProductEntity> @Query("SELECT * FROM products WHERE name = :name") fun getProductByName(name: String): Maybe<ProductEntity>
  • 79. RxJava 2 Flowable Maybe Single No data - Just onComplete onError Data onNext onSuccess onSuccess Update onNext - -
  • 81. But enough for today