Room Persistence Library

Well Google I/O 17 came out with a few interesting things on Android. One of them was the long coming was room persistence. Well persistence has been in Java quite some time and it was high time it had to come to Android ecosystem. This write up is my take on the persistence library.
Well I have seen developers still write CRUD helpers for sqlite in android

[SqliteHelper] []
1
2
3
4
5
6
7
8
9
10
11
12
public class SqliteHelper {
void read(){
dbhelper.getReadableDatabase().execute("/// kickass long query that spans across the screen");
// Ehh, some query builder writing sql statements
//convert it to a pojo -> Arghhh
}
void write(){}
}
  • Screams of languish *

Well the origins of the DAO,DTO and Entity pattern has been from the Mircosoft era of 1992(called as jet DAO/DTO) which is mostly used in state-less based architecture (HTTP) service has had a lot of advantages/disadvantages over a period of time. I feel using them ensures separation between parts of an application. And it is right to get it into android ecosystem because the entire approach of using databases in android was spaghetti all over. With the usage of “room” things will become much cleaner on the design pattern perspective.

I found DAO’s in the goto docs which represents params in the query like this

[MyDao] []
1
2
3
4
5
6
7
@Dao
public interface MyDao {
@Query("SELECT * FROM user WHERE age > :minAge")
public User[] loadAllUsersOlderThan(int minAge);
}

From my experience of backend there is another simple representational way of writing the same DAO. But I am not sure if this is accepted in the @Query validation processor.

[MyDao] []
1
2
3
4
5
6
7
@Dao
public interface MyDao {
@Query("SELECT * FROM user WHERE age > ?1") // well if you have two params then its ?1, ?2
public User[] loadAllUsersOlderThan(int minAge);
}

If there still exists business logic that evaluates entity and maps them to DTO. I believe an extended Mapper with MapperFactory can be used to constuct this DTO. Well before finishing this blog about persistence on a positive note. Well there few drawbacks with this design pattern like leaky abstraction & abstraction inversion.

You can add room into your project with this

1
2
3
4
5
6
7
8
dependencies{
compile 'android.arch.lifecycle:extensions:' + "$verison";
compile 'android.arch.persistence.room:runtime:' + "$verison";
annotationProcessor 'android.arch.lifecycle:compiler:' + "$verison";
annotationProcessor 'android.arch.persistence.room:compiler:' + "$verison";
}

The sample project of how to use it is in this link. I am still exploring about other architecture components and will definitely talk about how all of these things play together.