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.
No Direct Entity References
Unlike the greenDAO example above, with Room, a Thingy
cannot have a field for an OtherThingy
that Room is expected to manage. You could have a field for an OtherThingy
marked as @Ignore
, but then you are on your own for dealing with that field.
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.
Foreign Keys
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 does very little else with these keys.
Cascades on Updates and Deletes
Part of what you can place on a @ForeignKey
annotation are onUpdate
and onDelete
properties. These indicate what actions should be taken on this entity when the parent of the foreign key relationship is updated or deleted. There are five possibilities, denoted by ForeignKey
constants:
Constant Name | If the Parent Is Updated or Deleted… |
---|---|
NO_ACTION |
…do nothing |
CASCADE |
…update or delete the child |
RESTRICT |
…fail the parent’s update or delete operation, unless there are no children |
SET_NULL |
…set the foreign key value to null |
SET_DEFAULT |
…set the foreign key value to the column(s) default value |
NO_ACTION
is the default, though CASCADE
will be a popular choice.
Cascades on… Retrievals?
You cannot have an entity automatically retrieve related objects via a @Query
.
You can have an arbitrary POJO automatically retrieve related objects via a @Query
, by means of a @Relation
annotation.
This seeming inconsistency will be explored later in this chapter.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.