Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Room Multiple fields have the same columnName

I am facing with a specific problem with Room. I have an object

@Entity(tableName = "classifieds")
data class ClassifiedBean(
    @PrimaryKey
    @ColumnInfo(name = "id")
    @SerializedName("id")
    var id: String,

    @Embedded
    @SerializedName("client")
    var clientBean: ClientBean,

    @Embedded
    @SerializedName("location")
    var locationBean: LocationBean
)

Here I have my Object LocationBean and ClientBean.

The problem is inside my ClientBean, I have also a LocationBean with same attribute (address, postalCode, city, country...).

data class ClientBean(
    @ColumnInfo(name = "client_id")
    @SerializedName("id")
    var id: Int,

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

    @Embedded
    @SerializedName("location")
    var locationBean: LocationBean
)

here you can find my LocationBean

data class LocationBean (
    @ColumnInfo(name = "location_id")
    @SerializedName("locationId")
    var id: Int,

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

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

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

    @ColumnInfo(name = "postal_code")
    @SerializedName("postalCode")
    var postalCode: String,

)

Here my error :

error: Multiple fields have the same columnName: location_id. Field names: clientBean > locationBean > id, locationBean > id.

One of the solution is to create 2 different object with same attribute but I would like to know if they have another solution ?

Thank you for your help

like image 873
Tai Nguyen Avatar asked Jun 13 '19 13:06

Tai Nguyen


1 Answers

Try using prefix with embedded like @Embedded(prefix = "prefix_"). Hopefully, Changing your ClientBean class to below code will work fine

data class ClientBean(
        @ColumnInfo(name = "client_id")
        @SerializedName("id")
        var id: Int,

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

        @Embedded(prefix = "client_bean_")
        @SerializedName("location")
        var locationBean: LocationBean
)

Since when you use @Embedded, Room add fields of Embedded class as columns in same table. So when there is possibility of duplication of field names between embedded class and owner class try using prefix to avoid duplication. What Room will do after adding prefix it will add prefix before the column names for the embeded class. Refer to documentation to read more

like image 119
Mureed Hussain Avatar answered Sep 16 '22 15:09

Mureed Hussain