SQLite Made Easy : Room Persistence Library

Sunil Kuntal
MindOrks
Published in
3 min readOct 14, 2017

There is always space for improvement, no matter how long you’ve been in the business.

-Oscar De La Hoya

Lets start with a most obvious question about Room : Why should I use another library to manage my SQLite database when I am already well equipped with SQLite usage?

Answer of this question lies in below problem statements.

Major problem with SQLite usage is

  • There is no compile-time verification of raw SQL queries. For example if you write a SQL query with a wrong column name that does not exist in real database then it will give exception during run time and you can not capture this issue during compile time.
  • As your schema changes you need to update the affected SQL queries manually. This process can be time consuming and error prone.
  • You need to use lots of boilerplate code to convert between SQL queries and Java data objects.

All above concerns are taken care by Room persistence library that was introduced last month in Google I/O 2017. It is super easy to learn and reduce your efforts drastically.

Room provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite. Let’s start with how to add Room in your project.

Setup

  1. 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 highlighted line as shown below:
allprojects {
repositories {
jcenter()
maven { url 'https://maven.google.com' }
}
}

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

implementation "android.arch.persistence.room:runtime:1.0.0-beta2"

annotationProcessor "android.arch.persistence.room:compiler:1.0.0-beta2"

testImplementation "android.arch.persistence.room:testing:1.0.0-beta2"

implementation "android.arch.persistence.room:rxjava2:1.0.0-beta2"

How to Use Room :

There are three major components in Room

  1. Database : This component represents data holder. The annotated class should be an abstract class that extends RoomDatabase. At runtime, you can acquire an instance of it by calling Room.databaseBuilder() or Room.inMemoryDatabaseBuilder().

Example :

@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
public abstract UserDao userDao();
}

2. DAO : DAOs are the main component of Room and are responsible for defining the methods that access the database. All queries are written in DAO only.

Example :

@Dao
public interface UserDao {
@Query("SELECT * FROM user")
List<User> getAll();

@Query("SELECT * FROM user WHERE uid IN (:userIds)")
List<User> loadAllByIds(int[] userIds);

@Query("SELECT * FROM user WHERE first_name LIKE :first AND "
+ "last_name LIKE :last LIMIT 1")
User findByName(String first, String last);

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

@Delete
void delete(User user);
}

3. Entity : This component represents a database row of table. Each field of the entity is persisted in the database unless you annotate it with @Ignore .

Example

@Entity
class User {
@PrimaryKey
public int id;

public String firstName;
public String lastName;

@Ignore
Bitmap picture;

}

Now we have already defined Entity , DAO and Database class. To do operations on database below code can be used and remember to call below code in Worker thread.

AppDatabase mDb = Room.inMemoryDatabaseBuilder(context, AppDatabase.class).build(); // Get an Instance of Database class //defined above       UserDao mUserDao = mDb.getUserDao();// Get DAO object   User user = TestUtil.createUser(3);// Create User object to insert
user.setName("george");
mUserDao.insert(user); // Insert it in database

My personal experience with Room is :

  1. I found it easier than using SQLite directly.
  2. It makes you verify your database code during compile time.
  3. It makes your code more modular and readable as you divide your database code in three components like Entity , DAO and Database.

Be sure to 👏 below to recommend this article. It means a lot to me. Your Comments and suggestions are welcome.

Also, Let’s become friends on Linkedin , Facebook and Twitter

Reference:

Recommended Reading

--

--

Sunil Kuntal
MindOrks

Android lead, Unlocking Metaverse . Believe in learning and sharing. Figuring out ways to contribute back to society