AcidMammoth
AcidMammoth

Reputation: 61

Primary key not autogenerated using Room's Entity

I'm using Room Entity framework for a class called User and I set the user ID to be autogenerated.

I tried to create an user object using the ONLY constructor, since Room cannot pick between multiple constructors.

My class looks like this:

@Entity
public class User {

    @PrimaryKey(autoGenerate = true)
    @NonNull
    @ColumnInfo(name = "user_id")
    private Integer userID;

    @ColumnInfo(name = "first_name")
    private String firstName;

    @ColumnInfo(name = "last_name")
    private String lastName;

    public User(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public Integer getUserID() {
        return userID;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public void setUserID(Integer userID) {
        this.userID = userID;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

The object is created just like this: User user = new User("Gabriel", "Johnson");

I expected the ID to be 1, as I guess it will be incremented with every user that is created, beginning from 1. But the ID is null, the auto generation never happens.

Upvotes: 0

Views: 601

Answers (1)

ianhanniballake
ianhanniballake

Reputation: 199805

Room only auto generates the key when the object is inserted into the database - even then, it doesn't fill out your key in the object you inserted.

You should only expect the userId to be filled out when reading an entity from the database.

Upvotes: 3

Related Questions