The Room Approach

Room behaves a bit like other annotation-based Android ORMs, but when it comes to relations, Room departs from norms, in an effort to reduce the likelihood of threading problems.

Unlike the greenDAO example above, with Room, a Thingy cannot have a property for an OtherThingy that Room is expected to manage. You could have a property for an OtherThingy marked as @Ignore, but then you are on your own for dealing with that property.

The implication of an entity referencing another entity directly is that developers would expect that when Room retrieves the outer entity, that Room either will automatically retrieve the inner entity or will retrieve it lazily later on. The former approach avoids threading issues but runs the risk of loading more data than is necessary. The latter approach runs the risk of trying to do disk I/O on the main application thread.

This does not mean that you cannot have foreign keys. Room fully supports foreign key relationships, by way of a @ForeignKey annotation. This sets up the foreign keys in the appropriate tables… but that’s about it. Room also has a @Relation annotation, to allow you to retrieve related data… but it does not involve entities as much as you might think.

And all of that will (hopefully) make more sense with some examples, from the the MiscSamples module of the book’s primary sample project.

Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.