Room Persistence Library

Room Persistence Library

We know that to write a good responsive android app, you need to save data on disk.You need to use SQLite if you want to save big data.We want to get rid of SQLite boilerplate free code.Room an Object  Mapping library for SQLite.

Write boilerplate code for you

Usually, In the database the best practice to put your database access into certain interfaces.You define the interfaces Room provide the implementation.

Full SQLite support

Room Speaks SQL.Most important part of Room is it understands your SQL.So, the Part all those constants. Room actually gives all of this for free.

Compile time validation

Room defined to get compile-time guarantees.Room is going to give you an error at compile time.So it goes out and verifies your query against the schema you have defined, it tells you is something is wrong.

Incentivises best practices

You can basically create any java class.It doesn’t need to be annotated, there’s nothing special about POJO, and tell Room to return It.As long as whatever query it returns.Matches what you want it to return, Room will write the code for you.

Observability is important ?

We want to get notified when the data changes.and in Room, if you want to do this all you have to do tell it to return a LiveData and it will do it for you.Because it Knows your query, it knows what thing affect it.So it can let you know if that query changes.

This is the part where all these architecture components work well together.Room already knows about live data.

So your ViewModel all you would write is the data, from the data is call this query and this all it will do.Whenever that data changes, your UI will get a new update.

Adding Components to your Project

open the build.gradle file of  project  and add the line as shown below:

Open the build.gradle file for your app and add the artifacts that you need as dependencies:

Create Entity

Represents a class that holds a database row. For each entity, a database table is created to hold the items. You must reference the entity class in the Database class. Each field of the entity is persisted in the database unless you annotate it with @Ignore.

room entity

When a class is annotated with @Entity and is referenced in the entities property of a @Database annotation, Room creates a database table for that entity in the database.

Nested objects

you’d like to express a POJO as a cohesive whole in your database logic.In these situations, you can use the @Embedded annotation to represent an object that you’d like to decompose into its subfields within a table. You can then query the embedded fields just as you would for other individual columns.

Our User class can include a field of type Address. To store the composed columns separately in the table, include an Address field in the User class that is annotated with @Embedded, as shown in the following code snippet:

Indices and uniqueness

You might want to index certain fields in the database to speed up your queries. To add indices to an entity, include the indices property within the @Entity annotation.You can enforce this uniqueness property by setting the uniqueproperty of an @Index annotation to true.


Room allows you to define Foreign Key constraints between entities.

For example, if there’s another entity called Book, you can define its relationship to the User entity using the @ForeignKey annotation, as shown in the following code snippet:


You can tell SQLite to delete all books for a user if the corresponding instance of User is deleted by including onDelete=CASCADE in the @ForeignKey annotation.

Data Access Objects (DAO)

This component represents a class or interface as a Data Access Object (DAO). DAO are responsible for defining the methods that access the database. When generating the code at compile time, Room creates an implementation of this class.


Create a DAO method annotate with @Insert .Room generates an implementation that inserts all parameters into the database in a single transaction.

The following code snippet shows example queries:

It can return a long, which is the new rowId for the inserted item. If the parameter is an array or a collection, it should return long[] or List<Long> .


It uses a query that matches against the primary key of each entity.


Deletes a set of entities, given as parameters, from the database. It uses the primary keys to find the entities to delete.

Delete and Update method can return an int value instead, indicating the number of rows updated in the database.


It allows you to perform read/write operations on a database. Each @Query method is verified at compile time.

Room also verifies the return value of the query such that if the name of the field in the returned object doesn’t match the corresponding column names in the query response.

Querying multiple tables(JOIN)

Room allows you to write any query, so you can also join tables. Furthermore, if the response is an observable data type, such as Flowable or LiveData, Room watches all tables referenced in the query for invalidation.

The following code snippet shows how to perform a table join to consolidate information between a table containing users who are borrowing books.

Data type converters

You sometimes use a custom data type whose value you would like to store in the database in a single column. To add this kind of support for custom types, you provide a TypeConverter, which converts a custom class to and from a known type that Room can persist.

Create Database

The annotation defines the list of entities, and the class’s content defines the list of data access objects (DAOs) in the database. It is also the main access point for the underlying connection.

The annotated class should be an abstract class that extends RoomDatabase.

class must contain an abstract method that has 0 arguments and returns the class that is annotated with @Dao.


java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long periods of time.

At runtime, you can acquire an instance of it by calling Room.databaseBuilder() or Room.inMemoryDatabaseBuilder().

Download this project from GitHub.


Related Post

Lifecycle Aware Components



Fragment Tricks

ConstraintLayout 1.1.x

Leave a Reply

Your email address will not be published. Required fields are marked *