Pro Android with Kotlin


Download 5.42 Mb.
Pdf ko'rish
bet104/223
Sana04.11.2023
Hajmi5.42 Mb.
#1746807
1   ...   100   101   102   103   104   105   106   107   ...   223
Bog'liq
@de android telegram Pro Android with Kotlin Developing Modern Mobile

117
CHAPTER 8: APIs
abstract fun contactDao(): ContactDao
abstract fun personDao(): PersonDao
}
Inside the @Database annotation you declare all the entity classes used, and as abstract 
functions you provide factory methods for the DAO classes. You don’t have to implement 
this abstract database class. The Room library will automatically provide an implementation 
for you based on the signatures and the annotations! The version number will help you when 
upgrading to different data model versions; you’ll learn more about that in the following 
sections.
Entities
Next we implement the entity classes, which is extremely easy to do in Kotlin.
@Entity
data class Employee(
@PrimaryKey(autoGenerate = true) var uid:Int = 0,
var firstName:String,
var lastName:String)
@Entity
data class Contact(
@PrimaryKey(autoGenerate = true) var uid:Int = 0,
var emailAddr:String)
You can see that we need a primary key of type Int for each entity. autoGenerate = true 
takes care of automatically making it unique.
The column names from the database table defined by these entity classes match the 
variable names. If you want to change that, you can add another annotation: 
@ColumnInfo.@Entity
data class Employee(
@PrimaryKey(autoGenerate = true) var uid:Int = 0,
@ColumnInfo(name = "first_name") var firstName:String,
@ColumnInfo(name = "last_name") var lastName:String)
This would lead to using first_name and last_name as table column names.
Also, the table name is taken from the entity class name, like with Employee and Contact for 
these examples. You can also change this; just add the parameter tableName to the @Entity 
annotation as follows:
@Entity(tableName = "empl")
data class Employee(
@PrimaryKey(autoGenerate = true) var uid:Int = 0,
@ColumnInfo(name = "first_name") var firstName:String,
@ColumnInfo(name = "last_name") var lastName:String)



Download 5.42 Mb.

Do'stlaringiz bilan baham:
1   ...   100   101   102   103   104   105   106   107   ...   223




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