Paul Okeke
Paul Okeke

Reputation: 1414

How do i persist Custom Object within an object in Room

I have this Entity

data class Asset(
        @SerializedName("id")
        @Expose
        @PrimaryKey
        var id: String = "",

        @SerializedName("asset_name")
        @ColumnInfo(name="asset_name")
        @Expose
        var name: String = "",

        @SerializedName("asset_type_name")
        @ColumnInfo(name="asset_type_name")
        @Expose
        var typeName: String = "",

        @SerializedName("status")
        @Expose
        var status: Int = 0,

        @SerializedName("group")
        @Expose
        var group: Group? = null
    )

"Group" is also an Entity, so while persisting Asset is it possible to also Persist "Group" to its own Table if it doesn't already exist?

or shouldni simply just use TypeConverters and move on.

Upvotes: 1

Views: 46

Answers (1)

Alexander Egger
Alexander Egger

Reputation: 5300

Use can either use a foreign key or a nested object.

Using a foreign key in your example could look like this:

@Entity(foreignKeys = @ForeignKey(entity = Group.class,
                              parentColumns = "id",
                              childColumns = "group_id"))
data class Asset(

    // ...

    @ColumnInfo(name = "group_id")
    var groupId: Int? = null
)

In this case your application is responsible for fetching the Group based on the groupId as Room does not allow object references.

Embedding the object could look like this:

data class Asset(

    // ...

    @SerializedName("group")
    @Expose
    @Embedded
    var group: Group? = null
)

Note that in this case the fields of Group are embedded into the table of Asset.

Which of the two options to choose depends on the use case. Nevertheless both are preferable over using TypeConverters.

Upvotes: 1

Related Questions