0

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;
}

1 Answers1

0

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)
    },
    ...
)
Raul Sauco
  • 2,645
  • 3
  • 19
  • 22
  • It still not working... i did exaclly what you said but it allow me to insert duplicate usernames – Daniel blue Mar 07 '18 at 11:22
  • Could you check the table definition on the generated SQLite file? It might give a clue of where the error is. – Raul Sauco Mar 07 '18 at 13:40
  • @Danielblue, great to hear that, could you [mark the answer as accepted](https://stackoverflow.com/help/someone-answers) then please? Also, which of the methods did you use? `@Unique` or adding an `@Index` inside the entity annotation? – Raul Sauco Mar 07 '18 at 23:55
  • sure! It was @Unique – Daniel blue Mar 08 '18 at 09:24