Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 451
Arash Khoeini Avatar asked Jan 08 '23 10:01

Arash Khoeini


2 Answers

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();
like image 83
Artur Bakiev Avatar answered Jan 31 '23 03:01

Artur Bakiev


Apparently you can't do this with Sugar ORM. The documentation on their website doesn't say anything about the primary key or even having such an annotation. You should consider switching to OrmLite which I personally recommend and is known to work good with Android.

http://ormlite.com/sqlite_java_android_orm.shtml

like image 28
Theo Avatar answered Jan 31 '23 02:01

Theo