Search code examples
androidprimary-keysugarorm

How to set primary key in SugarORM


I'm using SugarORM for the first time and I have a quick question. How can I set one entity as primary key ? For example, I need something like this:

public class Student{
    @PrimaryKey
    private String studentId;
    private String name;
}

Is it possible? Thank you.


Solution

  • No way to specify primary key at the moment. But starting with sugar 1.4 there is an option to use @Unique attribute (https://github.com/satyan/sugar#sugarrecord):

    public class Book extends SugarRecord {
        @Unique
        String isbn;
        String title;
        String edition;
        /*...*/
        public Book(String isbn, String title, String edition) {
            this.isbn = isbn;
            this.title = title;
            this.edition = edition;
        }
    }
    

    It is not primary key but in many cases it does similar job (https://github.com/satyan/sugar#update-entity-based-on-unique-values):

    Book book = new Book("isbn123", "Title here", "2nd edition")
    book.save();
    
    // Update book with isbn123
    Book sameBook = new Book("isbn123", "New Title", "5th edition")
    sameBook.update();
    
    book.getId() == sameBook.getId();