120
CHAPTER 8: APIs
Nested Objects
Although it is not possible to define inter-object relations other than manually by foreign
keys, you can on the object side define a nesting of hierarchical objects. For example, from
the following employee entity:
@Entity
data class Employee(
@PrimaryKey(autoGenerate = true) var uid:Int = 0,
var firstName:String,
var lastName:String)
you can factor out the first and last names and instead write the following:
data class Name(var firstName:String, var lastName:String)
@Entity
data class Employee(
@PrimaryKey(autoGenerate = true) var uid:Int = 0,
@Embedded var name:Name)
Note that this does not have any impact on the database side of the data model. The
associated table will still have the columns uid, firstName, and lastName. Since the
database identity of such an embedded object is tied to the name of its fields, if you have
several embedded objects of the same embedded type, you must disambiguate the names
by using a prefix attribute as follows:
data class Name(var firstName:String, var lastName:String)
@Entity
data class Employee(
@PrimaryKey(autoGenerate = true) var uid:Int = 0,
@Embedded var name:Name,
@Embedded(prefix="spouse_") var spouseName:Name)
This makes the table have the columns uid, firstName, lastName, spouse_firstName, and
spouse_lastName.
If you like, inside the embeddable class, you can use Room annotations. For example, you
can use the @ColumnInfo annotation to specify custom column names.
data class Name(
@ColumnInfo(name = "first_name") var firstName:String,
@ColumnInfo(name = "last_name") var lastName:String)
@Entity
data class Employee(
@PrimaryKey(autoGenerate = true) var uid:Int = 0,
@Embedded var name:Name)
Do'stlaringiz bilan baham: |