Room Persistance Library

Posted By : Rahul Baboria | 28-Jan-2018

Introduction : 

 

In the year 2017, Google announced Room Persistance Library for using SQLite DB  which act as an abstract layer. We can run any SQLite database operations and access DB more fluently. Room works at compile time, it throws an exception at compile time rather than a runtime crash.We can use Room to observe changes in data stored in a DB, and track those changes with objects called LiveData objects. It also supports thread constraints like we don't want to run heavy SQL operations on the main thread as it will slow down the application.

 

COMPONENTS OF ROOM:

 

There are three main components of room :

1. Database: It is a class which uses annotation to define the list of entities, database version. This class contains a list of Data access objects which will be used.
2. Entity: It represents data from a single table row, Annotation is used to construct entity.Each entity is persisted into its own table.
3. DAO (Data Access object): It defines the method that accesses the database, using annotation to bind SQL to each method.

 

ADD To Your Project :

 

 

compile 'android.arch.persistence.room:runtime:1.0.0-alpha1';
annotationProcessor 'android.arch.persistence.room:compiler:1.0.0-alpha1' ;

 

Create Entity Class:

 

Create an entity say, Employee. This class defines attributes of your table, there should be a field which is primary key by annotating it with @PrimaryKey . It has property to auto-generate values which autogenerate ID's and assigns automatically. This Class will be annotated with @Entity and table name. Finally, Room will create a table with the name and given attributes.

 

@Entity(tableName = "employee")
public class Employee {

    @PrimaryKey(name = "emp_id")
    private int employeeId;

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

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

    @ColumnInfo(name = "role")
    private String role;

    public int getEmployeeId() {
        return employeeId;
    }

    public void setEmployeeId(int employeeId) {
        this.employeeId = employeeId;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }

}

 

Create DAO Interface:

Create a DAO using an interface by annotating this class name with @Dao. Room will automatically generate an implementation of defined methods inside this interface. To perform CRUD operations, there are basically four annotations @Query, @Insert, @Update, @Delete. To perform read operation on DB @Query annotation is used.

 

 

@Dao
public interface EmployeeDao {

    @Query("SELECT * FROM employee")
    List<Employee> getAll();


    @Query("SELECT * FROM employee where emp_id LIKE  :employeeId")
    Employee findByEmployeeId(int EmployeeId);

    @Query("SELECT COUNT(*) from employee")
    int countEmployees();

    @Insert
    void insertAll(Employee... employees);

    @Delete
    void delete(Employee employee);
}

 

Create a database holder Class

 

Create a class says MyFirstRoomDatabase extends RoomDatabase, define a list of entities and database version. Annotate the class with @Database annotation. It is a better way, if we use singleton approach for the database, so we need to create a static method that will return an instance of MyFirstRoomDatabase.

 

 

@Database(entities = {Employee.class}, version = 1)
public abstract class MyFirstRoomDatabase extends RoomDatabase {

    private static MyFirstRoomDatabase INSTANCE;

    public abstract EmployeeDao employeeDao();

    public static MyFirstRoomDatabase getMyFirstRoomDatabase(Context context) {
        if (INSTANCE == null) {
            INSTANCE =
                    Room.databaseBuilder(context.getApplicationContext(), MyFirstRoomDatabase.class, "employee-database")
                            .allowMainThreadQueries() //choose thread
                            .build();
        }
        return INSTANCE;
    }

    public static void destroyInstance() {
        INSTANCE = null;
    }
}

Thanks.

About Author

Author Image
Rahul Baboria

Rahul Baboria is having good knowledge over Android Application.

Request for Proposal

Name is required

Comment is required

Sending message..