Fork me on GitHub

Entities and Relationships

To create a persistent entity, just extend it with SugarRecord.

public class Book extends SugarRecord {
    String name;
    // You must provide an empty constructor
    public Book() {}
}

Or you can use annotations@Table, but then you should define a private Long id field

@Table
public class Book {
    private Long id;

    public Book(){
    }

    public Book(String title, String edition){
        this.title = title;
        this.edition = edition;
    }

    public Long getId() {
        return id;
    }
}

This class would automatically map to a table named book.

Now that you have the entity, start defining their properties.

public class Book extends SugarRecord {
  String name;
  String ISBN;
  String title;
  String shortSummary;
}

This would create corresponding columns in the book table. Column names would be name, ISBN, title and short_summary. Notice the conversion from shortSummary to short_summary. This is the convention followed in Sugar. (Next step: making it configurable.)

To skip a property from persisting, annotate it as Ignore.

In below example, name would not be persisted, neither would a corresponding column be created for this property.

public class Book extends SugarRecord {
  @Ignore
  String name;

  String ISBN;
}

Lets bring another entity into picture.

public class Author extends SugarRecord {
  String name;

  public Author() {}

  // Get all books of this author
  List<Book> getBooks() {
      return Book.find(Book.class, "author = ?", new String{getId()})
  }
}

Each book has an author and that would be represented by having a reference to Author in Book class, as follows:

public class Book extends SugarRecord {
  String name;
  String ISBN;
  String title;
  String shortSummary;

  // defining a relationship
  Author author;
}

This would store a column named author in the book table. This would help with one-to-many relationships.

  • You should save Author before saving Book.

  • We will try to improve how we handle one-to-many relationships

  • One-to-one relationship doesn't work yet

List<Book> books = Book.find(Book.class, "author = ?", new String{author.getId()});
Book book = Book.findById(Books.class, 1);
Author author = book.author;