118
CHAPTER 8: APIs
While it is generally a good idea to have a single integer-valued primary key, you can also
use a combined key. For that aim, there is an additional annotation parameter in @Entity.
Here’s an example:
@Entity(tableName = "empl",
primaryKeys = tableOf("first_name","last_name"))
data class Employee(
@ColumnInfo(name = "first_name") var firstName:String,
@ColumnInfo(name = "last_name") var lastName:String)
Entities can also have fields that will not be persisted. From a design perspective, this is
maybe not a good idea, but if you need such a field, you can add it and use the annotation
@Ignore as follows:
@Entity(tableName = "empl")
data class Employee(
@PrimaryKey(autoGenerate = true) var uid:Int = 0,
var firstName:String = "",
var lastName:String = "",
@Ignore var salary:Int)
Because of the way Room is implemented, if you add such an @Ignore annotation, all the
fields must have default values assigned, even if unused.
Relationships
Room by design doesn’t allow direct relationships between entities. You cannot, for
example, add a list of Contact entities as a class member of an Employee entity. However, it
is possible to declare foreign key relationships, which helps in maintaining data consistency.
To do so, add a foreignKeys annotation attribute, as in the following code snippet:
@Entity(
foreignKeys = arrayOf(
ForeignKey(entity = Employee::class,
parentColumns = arrayOf( "uid" ),
childColumns = arrayOf( "employeeId" ),
onDelete = ForeignKey.CASCADE,
onUpdate = ForeignKey.CASCADE,
deferred = true)),
indices = arrayOf(
Index("employeeId"))
)
@Entity
data class Contact(
@PrimaryKey(autoGenerate = true) var uid:Int = 0,
var employeeId:Int,
var emailAddr:String)
Do'stlaringiz bilan baham: |