Fork me on GitHub

Entities and Relationships

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

public class Book extends SugarRecord<Book> {
  String name;
}

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<Book> {
  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<Book> {
  @Ignore
  String name;

  String ISBN;
}

Lets bring another entity into picture.

public class Author extends SugarRecord<Author> {
  String name;
}

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<Book> {
  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-one and one-to-many relationships.

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