How can I set autoGenerate in the primaryKeys list of @Entity?

26
October 20, 2018, at 02:30 AM

I'm new for the Android Room library. I want to create a table with two primary key. I also want to set autoGenerate to these two primary key but I don't know how to do it. The detail of the code is shown below:

@Entity(primaryKeys = {"userId", "planName"},
    foreignKeys = @ForeignKey(entity = User.class,
    parentColumns = "id",
    childColumns = "userId",
    onDelete = CASCADE))
public class Plan {
    public int userId;
    @NonNull
    public String planName;
}

Thank you very much!

Answer 1

Welcome to Stackoverflow.

Technically you can't have 2 primary keys. It's by definition a single index which has UNIQUE constraint on it. Although it can be applied to 2 columns at once. Meaning that the combination of those 2 columns should be unique but each one separately can contain repetitive values.

And as for the autoGenerate, a primary key can only be auto generated if it is of type integer and a single column. You can't have a composite primary key be auto generated.

Answer 2

Generally, a primary key should be a single column that uniquely identifies each row. If you want to also guarantee the uniqueness of the pair (userId, planName), you should just add a UNIQUE constraint. Additionally, you may want to add an index to the pair of columns.

READ ALSO
Android - What is the difference between /proc/net/tcp and /proc/pid/net/tcp

Android - What is the difference between /proc/net/tcp and /proc/pid/net/tcp

Can I assume that /proc/net/tcp is a sum of all the /proc/pid/net/tcp? If not what are the differences? Are the root/system tcp sessions managed separately?

48
Create A Calendar App Widget with Android Studio

Create A Calendar App Widget with Android Studio

I have been asked to develop an appointment application college assignmentRight now my progress is on creating a Calendar App Widget

45
Using moveTaskToBack() in onBackPressed()

Using moveTaskToBack() in onBackPressed()

Is it okay to use moveTaskToBack() method in onBackPressed() event rather than finishing the activity?

37
Observable keeps emitting after Db operation was performed in SqlBrite..

Observable keeps emitting after Db operation was performed in SqlBrite..

i have a case where in the flatmap keeps emitting even after the "doOnComplete" is calledAnd I have noticed that whenever i call a insertMethod in SqlBrite the flatMap starts emitting again

43