Why Android Room ?

Tanushree
Nybles
Published in
4 min readOct 28, 2021

Do you already have an Android project that uses SQLite for data persistence? If so, you can migrate it to Room!

For those who don’t know why Room database is preferred now-a-days, here is your thing.😎 So, buckle up and get into your rooms to explore ROOM 😆

Before getting into the implementation part, let’s first know about what ROOM is and why it is preferred over SQLITE database 👁️‍🗨️!

What is Room?

Room is a persistence library that provides an abstraction layer over the SQLite database to allow a more robust database. With the help of room, we can easily create the database and perform CRUD operations very easily.

  • Compile-time verification of SQL queries.
  • Convenience annotations that minimize repetitive and error-prone boilerplate code.
  • Streamlined database migration paths.

Room vs SQLite

  1. sqlite — Uses SQLiteOpenHelper and traditional SQLite interfaces.
  2. room — Replaces implementation with Room and provides migrations.

Each one of these uses the same UI layer, applying the Model-View-Presenter design pattern and working with a Repository class.

Room is an ORM, Object Relational Mapping library. In other words, Room will map our database objects to Java objects. Room provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite.

Difference between SQLite and Room persistence library:-

  • In case of SQLite, there is no compile-time verification of raw SQLite queries. But in Room, there is SQL validation at compile time.
  • You need to use lots of boilerplate code to convert between SQL queries and Java data objects. But, Room maps our database objects to Java Object without boilerplate code.
  • As your schema changes, you need to update the affected SQL queries manually. Room solves this problem.
  • Room is built to work with LiveData and RxJava for data observation, while SQLite does not.

Components of Room DB

This diagram shows a basic form of architecture components of which Room is a part:

As clear from above diagram, there are three main components of RoomDB :

  • Entity: Entity is a modal class that is annotated with @Entity. This class has variables that will be our columns and the class is our table.
  • Database: It is an abstract class where we will be storing all our database entries which we can call Entities.
  • DAO: The full form of DAO is a Database access object which is an interface class with the help of it we can perform different operations in our database.

Now, let’s discuss the implementation of the main components of Room database :

Create an Entity

Before we get started with modeling our entities, we need to know some useful annotations and their attributes.

@Entity — every model class with this annotation will have a mapping table in the database.

  • foreignKeys — names of foreign keys
  • indices — list of indicates on the table
  • primaryKeys — names of entity primary keys
  • tableName

@PrimaryKey — as its name indicates, this annotation points the primary key of the entity. autoGenerate — if set to true, then SQLite will be generating a unique id for the column

@PrimaryKey(autoGenerate = true)

@ColumnInfo — allows specifying custom information about column

@ColumnInfo(name = “column_name”)

@Ignore — field will not be persisted by Room

@Embeded — nested fields can be referenced directly in the SQL queries.

Now, let’s create an Entity, named as word and later, Objects of this class will be added to the database.

To do this:

  • Create a class named word .
  • Add @Entity annotation on the class.
  • Add ID, content, and title fields.
  • Important: mark at least one field with @PrimaryKey annotation.

Use alt+insert to implement constructor, override getter and setter, and optionally override equals or toString.

Tip:

You can auto generate unique keys by annotating the primary key as follows: @Entity(tableName = “word_table”)public class Word {

DAO

DAOs define all methods to access the database, annotated with @Dao annotation. The DAO acts as a contract to perform CRUD operations on data within a database.

The following code will:

  • Create an interface, marked with @Dao annotation.
  • Add methods for CRUD operations.

RoomDB

Now, we have table defined as word_table and CRUD methods defined via WordDao. The last piece of the database puzzle is the database itself.

We will have to:

  • Create an abstract class WordRoomDatabse which extends RoomDatabase.
  • Add version and entities to database as @Database(entities = {word.class}, version = 1).
  • Add abstract methods of all DAO’s where the returned DAO object will be constructed by Room for database interactions.

Some things to remember:

  • Version number is changed to update the database structure, when required in future updates
  • The database file name must end with the .db extension
  • Creating an instance of a database is quite costly so we will apply a Singleton Pattern to create and use already instantiated single instance for every database access.

These were some important components of using Room Database in your android application. Wanna get some pro tips for using Room database? Do check this article out!

Room offers many other features like LiveData for keeping the data source updated all the time and RxAndroid support for reactive programming.

You must implement database interactions to take the feel of a real world project. To begin with, you may refer building a basic Note Application app . Check out the sample application here !

About me :)

I am Tanushree, second year B.Tech student at IIIT Allahabad, member of AppD team in GDSC, IIITA.

Do check out my GitHub and reach me at LinkedIn.

Thank you so much for reading!😊

--

--