Mallow's Blog

An Introduction to Room Persistence Library in Android Development

It is not a very difficult task for Android developers to store raw data into a database for internal storage. But still they wish to have an efficient library to overcome boilerplate codes and compile-time verification for queries, here comes the relief Google announced Room Library in Google Developer meet 2017.

The Room is a persistence library, part of the Android Architecture Components. It makes it easier to work with SQLiteDatabase objects in your app, decreasing the amount of boilerplate code and verifying SQL queries at compile time.

There are three major components in Room:

Entity: represents data for a single table row, constructed using an annotated java data object. Each entity is persisted into its own table.

DAO: (Data Access Object) defines the method that accesses the database, using annotation to bind SQL to each method.

Database: is a holder class that uses annotation to define the list of entities and database version. This class content defines the list of DAOs.

room_architecture

Annotations in Room Persistence Library

Annotations Purpose
@Entity Creates an SQLite table in the database using a data model class.
@Dao Create a Data Access Object in the database using an interface class.
@Database A class with this annotation will create an abstraction for the Data Access Object.
@PrimaryKey A variable with this annotation will set a primary key for the table.
@Insert Inserts parameters into the table.
@Update Updates parameters of an existing table.
@Delete Deletes parameters of an existing table.
@Query Running SQL query method within the table
@Ignore Ignores the parameter form the Room database

 

Let’s look at a sample implementation:

1. Add these dependencies in module build.gradle

// Room (use 1.1.0-beta3 for latest beta)
implementation "android.arch.persistence.room:runtime:1.0.0"
annotationProcessor "android.arch.persistence.room:compiler:1.0.0"

2. Add the Google Maven repository

Android Studio projects aren’t configured to access this repository by default.

To add it to your project, open the build.gradle file for your project (not the ones for your app or module) and add the google() repository as shown below:

allprojects {
    repositories {
        jcenter()
        google()
    }
}

3. Defining the Table

The class is annotated with @Entity to mark as a table. To make field primary key, you need to annotate a field with @PrimaryKey and property autoGenerate which assign automatic IDs. The room will create a user table with defined attributes.

@Entity(tableName = "user")
public class User {

    @PrimaryKey(autoGenerate = true)
    private int uid;

    @ColumnInfo(name = "first_name")
    private String firstName;

    @ColumnInfo(name = "last_name")
    private String lastName;

    @ColumnInfo(name = "age")
    private int age;

//...getters and setters
}

4. Creating the Data Access Object (DAO)

This class is annotated with @Dao annotation. 

@Dao
public interface UserDao {

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

    @Query("SELECT * FROM user where first_name LIKE  :firstName AND last_name LIKE :lastName")
    User findByName(String firstName, String lastName);

    @Query("SELECT COUNT(*) from user")
    int countUsers();

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

    @Delete
    void delete(User user);
}

5. Database Creation

Create a database holder called AppDatabase extends RoomDatabase, we will define a list of entities and database version. The class is annotated with @Database annotation. It is good practice to use singleton approach for the database, so you need to create a static method which will return an instance of AppDatabase.

@Database(entities = {User.class}, version = 1)

public abstract class AppDatabase extends RoomDatabase{

public abstract UserDao userDao();

}

6. One to Many Relation

@ForeignKey is used to one to many relationships. Consider each user having many pets, it can be achieved using following example. onDelete = CASCADE is used delete the rows when that user has been deleted from the User table.

@Entity(foreignKeys = @ForeignKey(entity = User.class,
                                  parentColumns = "id",
                                  childColumns = "userId",
                                  onDelete = CASCADE))
public class Repo {
    @PrimaryKey public final int id;
    public final String name;
    public final int userId;

    public Repo(final int id, String name, final int userId) {
        this.id = id;
        this.name = name;
        this.userId = userId;
    }
}

@Embedded is used for having nested fields in the table. For example, user having address can be related using @Embedded.

@Entity
public class User {
    @PrimaryKey public final int id;

@ColumnInfo(name = "full_name")
    public final String name;

@Embedded
    public final Address address;

    public User(int id, String name, Address address) {
        this.id = id;
        this.login = login;
        this.address = address;
    }
}

Conclusion:

Android developers now feel very easy and convenient to handle raw data and make queries with Room Persistent Library.

 


Bringe Raj,
Android Development Team,
Mallow Technologies.

Leave a Reply

%d bloggers like this: