SlideShare una empresa de Scribd logo
1 de 83
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

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 CodeAlistair McKinnell
 
Oracle business intelligence publisher – developer training
Oracle business intelligence publisher – developer trainingOracle business intelligence publisher – developer training
Oracle business intelligence publisher – developer trainingitprofessionals 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 IDEHimanshiSingh71
 
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 210Mahmoud 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 ScalaJorge 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 modelsMariaDB 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 keynoteEmil Eifrem
 
11. session 11 functions and objects
11. session 11   functions and objects11. session 11   functions and objects
11. session 11 functions and objectsPhúc Đỗ
 
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 inputuanna
 
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 italyFabio Collini
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecLoï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 TurinFabio 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 MilanFabio Collini
 
Software architecture2008 ejbql-quickref
Software architecture2008 ejbql-quickrefSoftware architecture2008 ejbql-quickref
Software architecture2008 ejbql-quickrefjaiverlh
 

La actualidad más candente (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 a 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 RoomNelson Glauber Leal
 
Micro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateMicro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateKiev ALT.NET
 
Wicket KT part 2
Wicket KT part 2Wicket KT part 2
Wicket KT part 2stuq
 
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, 2012Anton 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 modelsKostyantyn Stepanyuk
 
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 EclipseHeiko 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 KrennJavaDayUA
 
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.pdfShaiAlmog1
 
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 Waytdc-globalcode
 
Improving Correctness with Types Kats Conf
Improving Correctness with Types Kats ConfImproving Correctness with Types Kats Conf
Improving Correctness with Types Kats ConfIain 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 examplesNebojš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.docxhoney725342
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기Arawn Park
 
Reactive clean architecture
Reactive clean architectureReactive clean architecture
Reactive clean architectureViktor Nyblom
 
Getting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NETGetting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NETTomas Jansson
 
Working With JQuery Part1
Working With JQuery Part1Working With JQuery Part1
Working With JQuery Part1saydin_soft
 

Similar a 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
 

Más de 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 timesSergi 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 talkSergi 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 FlowSergi 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 databaseSergi 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 canvasSergi Martínez
 
Introduction to Android Fragments
Introduction to Android FragmentsIntroduction to Android Fragments
Introduction to Android FragmentsSergi Martínez
 
Creating multillingual apps for android
Creating multillingual apps for androidCreating multillingual apps for android
Creating multillingual apps for androidSergi 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ª parteSergi Martínez
 

Más de 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
 

Último

Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 

Último (20)

Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 

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