Creating the Data Access Layer
Now that you have something to write into the database, you need some way to actually write it, and a way to retrieve it again. The most common pattern is to have a dedicated class to deal with this for each class--a Data Access Object class, also known as a DAO. In Room, however, all you have to do is declare what they should look like using an interface; Room will write the implementation code for you. You define your queries using the @Query
annotation on a method, like this:
@Query(“SELECT * FROM users WHERE _id = :id”) public User selectById(long id);
This has a huge advantage over traditional O/R mapping layers in that you can still write any form of SQL query, and let Room figure out how to convert it into the object model you ask for. If it can't write the code, you get an error at compile time, rather than potentially having your app crash for your users. This also has an additional advantage: Room can bind your SQL queries to non-entity classes, allowing...