Pro Android with Kotlin


Download 5.42 Mb.
Pdf ko'rish
bet108/223
Sana04.11.2023
Hajmi5.42 Mb.
#1746807
1   ...   104   105   106   107   108   109   110   111   ...   223
Bog'liq
@de android telegram Pro Android with Kotlin Developing Modern Mobile

121
CHAPTER 8: APIs
Using Indexes
To improve database query performance, you can declare one or more indexes to use on 
certain fields or field combinations. You don’t have to do that for the unique key; this is done 
automatically for you. But for any other index you want to define, write something like this:
@Entity(indices = arrayOf(
Index("employeeId"),
Index(value = arrayOf("country","city"))
)
)
data class Contact(
@PrimaryKey(autoGenerate = true) var uid:Int = 0,
var employeeId:Int,
var emailAddr:String,
var country:String,
var city:String)
This adds an index that allows for fast queries using the foreign key field employeeId and 
another one for fast queries given both country and city.
If you add unique = true as an attribute to the @Index annotation, Room will make sure the 
table cannot have two entries with the same value for that particular index. As an example, 
we can add a Social Security number (SSN) field to Employee and define an unique index for 
it, as shown here:
@Entity(indices = arrayOf(
Index(value = arrayOf("ssn"), unique = true)
)
)
data class Employee(
@PrimaryKey(autoGenerate = true) var uid:Int = 0,
var ssn:String,
@Embedded var name:Name)
If you now try to add two employees with the same SSN to the database, Room will throw 
an exception.
Data Access: DAOs
Data access objects (DAOs) provide the logic to access the database. We have already seen 
that inside the database declaration we had to list all DAOs in factory methods as follows:
@Database(entities =
arrayOf(Employee::class, Contact::class),
version = 1)
abstract class MyDatabase : RoomDatabase() {
abstract fun employeeDao(): EmployeeDao
abstract fun contactDao(): ContactDao
abstract fun personDao(): PersonDao
}



Download 5.42 Mb.

Do'stlaringiz bilan baham:
1   ...   104   105   106   107   108   109   110   111   ...   223




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling