Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible using String as PrimaryKey in Android Room

Tags:

I use uuid in my java backend server. So I need to use that uuid in room android to make sure entities are sync'd properly. I am aware of Is it possible to apply primary key on the text fields in android database and text as primarykey in android. I want to create something like this

@Entity(tableName = CrewColumns.TABLE_NAME)
@TypeConverters(BigDecimalConverter::class)
@JsonIgnoreProperties(ignoreUnknown = true)
class Crew() {
    constructor (uuid: String) : this() {
        this.uuid = uuid;
    }

    /**
     * The unique ID of the item.
     */
    @PrimaryKey
    @ColumnInfo(name = CrewColumns.UUID)
    var uuid: String = ""
    @ColumnInfo(name = CrewColumns.NAME)
    var name: String = ""
}

Will it be a problem with Room (DAO etc)? Thank you.

like image 417
ThomasEdwin Avatar asked Dec 05 '17 08:12

ThomasEdwin


People also ask

What is primary key in Android Studio?

implements Annotation. android.arch.persistence.room.PrimaryKey. Marks a field in an Entity as the primary key. If you would like to define a composite primary key, you should use primaryKeys() method. Each Entity must declare a primary key unless one of its super classes declares a primary key.

What are the two annotations that every entity object class will have in room?

We'll use two annotations – @Embedded and @Relation. As I mentioned before – @Embedded allows nested fields to be referenced directly in the SQL queries. @Relation describes relations between two columns. We have to specify the parent column name, entity column name and entity class.

What is entity in Android room database?

When you use the Room persistence library to store your app's data, you define entities to represent the objects that you want to store. Each entity corresponds to a table in the associated Room database, and each instance of an entity represents a row of data in the corresponding table.


1 Answers

Yes, you can use a String as a @PrimaryKey.

Additionally, I also recommend making use of Kotlin's data class to simplify your entities. For example:

@Entity
data class Crew(@PrimaryKey val uuid: String, val name: String) {
    // Put any functions or other members not initialized by the constructor here
}
like image 181
juanmeanwhile Avatar answered Oct 19 '22 06:10

juanmeanwhile