Blogs arrow How to implement ROOM database in android

How to implement ROOM database in android

line

Jan 28, 2021

s3bugket

Room Database

Introduction 

For Example:

Proven Reasons why use Room ?
For any schema change, the RoomDB automatically updates the query thus making the querying simpler. Also, RoomDB enhances the querying time and results are returned faster when the query is executed on the selected fields. The DAO inheritance feature makes it more popular. Last but not the least the desired output is higher with lesser code usage. It can also be easily integrated with other architecture components
Benefits of ROOM vs SQLite
  • In SQLite, The compile time verification of raw queries are not available as Room provides such features 
  • Room is designed to work with LiveData and RxJava for data observation, on the other hand SQLite does not support these features 
  • The SQL queries require lots of boilerplate code to convert into Java data objects whereas, In Room Database it is not required and hence lite to use
By using annotations, we can define our databases, tables, and operations. Room will automatically translate these annotations into SQLite instructions/queries to perform the corresponding operations into the database engine.
Components of Room DB
room-db

Room Database Architecture

Data Access Object. This is the interface where we set our SQL queries. @Insert, @Query, @Update@Delete.

@Insert cannot return an int.

@Update and @Delete can return an int which represents the number of rows changed/deleted.

Implementation of Room

Now in the coming sections, lets focus on using Room to create an application for maintaining employee data

Project Structure 

project-structure

file component

Employee.java

MyDao.java

Employee employee = new Employee();

employee.setId(id);
employee.setName(name);
employee.setEmail(email);

HomeActivity.myAppDatabase.myDao().addEmployee(employee);

By following the above steps, we would be able to successfully use Room in the Employee master application. Please note that the time taken for the same was very less when compared to using the SQLite as we did not have to write any queries. You can know more about Room Database by going through the following links:

https://medium.com/androiddevelopers/7-steps-to-room-27a5fe5f99b2

https://medium.com/androiddevelopers/understanding-migrations-with-room-f01e04b07929

https://stackoverflow.com/questions/50650077/sqlite-database-vs-room-persistence-library

 

vijay-pic

WRITTEN BY

Vijay M

lingam-pic

REVIEWED BY

Naveen Lingam

More Blogs

line