androiddatabasesqlitegreendaogreendao3

Greendao 3, make users table with no duplicate user names


I ask this question after searching for hours for the solution to this problem and did not find it. I have build a database with three columns: username, password and age. I am able to isert new users and update them, but I want it to be impossible to insert two identical user names. I know how to do it in sqlite but in greendao it just does not go for me. thank you.

here is my UsersClass:

@Entity(nameInDb = "users")
public class Users{

    @Id(autoincrement = true)
    private Long id;

    @NotNull
    private String userName;

    @NotNull
    private String password;

    @NotNull
    private int age;
}

Solution

  • The @Unique annotation should work for you.

    @Entity(nameInDb = "users")
    public class Users{
    
        @Id(autoincrement = true)
        private Long id;
    
        @Unique
        private String userName;
    
        @NotNull
        private String password;
    
        @NotNull
        private int age;
    }
    

    If you need to customize further you can add options to the @Entity annotation

    @Entity(
        ...
        // Define indexes spanning multiple columns here.
        indexes = {
                @Index(value = "name DESC", unique = true)
        },
        ...
    )