View on GitHub

reads

https://yazansneneh.github.io/reads/

Room

Setup to use room

Explination:

Sample implementation

  1. Data entity
     @Entity
    public class User {
     @PrimaryKey
     public int uid;
    
     @ColumnInfo(name = "first_name")
     public String firstName;
    
     @ColumnInfo(name = "last_name")
     public String lastName;
    }
    
  2. Data access object (DAO)
    • like i mentioned eariler it provide me the methods i need to perform crud operations on database.
@Dao
public interface UserDao {
    @Query("SELECT * FROM user")
    List<User> getAll();

    @Query("SELECT * FROM user WHERE uid IN (:userIds)")
    List<User> loadAllByIds(int[] userIds);

    @Query("SELECT * FROM user WHERE first_name LIKE :first AND " +
           "last_name LIKE :last LIMIT 1")
    User findByName(String first, String last);

    @Insert
    void insertAll(User... users);

    @Delete
    void delete(User user);
}
  1. Database
    • the class should have following:
      • must be annotated with a @Database annotation that includes an entities array that lists all of the data entities associated with the database.
      • must be an abstract class that extends RoomDatabase.
      • For each DAO class that is associated with the database, the database class must define an abstract method that has zero arguments and returns an instance of the DAO class.
@Database(entities = {User.class})
public abstract class AppDatabase extends RoomDatabase {
    public abstract UserDao userDao();
}

Usage of created classes.

Anatomy of an entity

Define relationships between objects

Define relationships

Define one-to-one relationships
@Entity
public class User {
    @PrimaryKey public long userId;
    public String name;
    public int age;
}

@Entity
public class Library {
    @PrimaryKey public long libraryId;
    public long userOwnerId;
}
Define one-to-many relationships
@Entity
public class User {
    @PrimaryKey public long userId;
    public String name;
    public int age;
}

@Entity
public class Playlist {
    @PrimaryKey public long playlistId;
    public long userCreatorId;
    public String playlistName;
}
Define many-to-many relationships
@Entity
public class Playlist {
    @PrimaryKey public long playlistId;
    public String playlistName;
}

@Entity
public class Song {
    @PrimaryKey public long songId;
    public String songName;
    public String artist;
}

@Entity(primaryKeys = {"playlistId", "songId"})
public class PlaylistSongCrossRef {
    public long playlistId;
    public long songId;
}

Accessing data using Room DAOs

Anatomy of a DAO

@Dao
public interface UserDao {
    @Insert
    void insertAll(User... users);

    @Delete
    void delete(User user);

    @Query("SELECT * FROM user")
    List<User> getAll();
}