package

androidx.room

Overview

Room is a Database Object Mapping library that makes it easy to access database on Android applications.

Rather than hiding the details of SQLite, Room tries to embrace them by providing convenient APIs to query the database and also verify such queries at compile time. This allows you to access the full power of SQLite while having the type safety provided by Java SQL query builders.

There are 3 major components in Room.

  • Database: This annotation marks a class as a database. It should be an abstract class that extends RoomDatabase. At runtime, you can acquire an instance of it via Room.databaseBuilder or Room.inMemoryDatabaseBuilder.

    The database class defines the list of entities and data access objects in the database. It is also the main access point for the underlying connection.

  • Entity: This annotation marks a class as a database row. For each Entity, a database table is created to hold the items. The Entity class must be referenced in the Database#entities array. Each field of the Entity (and its super class) is persisted in the database unless it is denoted otherwise (see Entity docs for details).
  • Dao: This annotation marks a class or interface as a Data Access Object. Data access objects are the main components of Room that are responsible for defining the methods that access the database. The class that is annotated with Database must have an abstract method that has 0 arguments and returns the class that is annotated with Dao. While generating the code at compile time, Room will generate an implementation of this class.

    Using Dao classes for database access rather than query builders or direct queries allows you to keep a separation between different components and easily mock the database access while testing your application.

Below is a sample of a simple database.
 // File: Song.java
  @Entity
 public class Song {
    @PrimaryKey
   private int id;
   private String name;
    @ColumnInfo(name = "release_year")
   private int releaseYear;
   // getters and setters are ignored for brevity but they are required for Room to work.
 }
 // File: SongDao.java
  @Dao
 public interface SongDao {
    @Query("SELECT * FROM song")
   List<Song> loadAll();
    @Query("SELECT * FROM song WHERE id IN (:songIds)")
   List<Song> loadAllBySongId(int... songIds);
    @Query("SELECT * FROM song WHERE name LIKE :name AND release_year = :year LIMIT 1")
   Song loadOneByNameAndReleaseYear(String first, int year);
    @Insert
   void insertAll(Song... songs);
    @Delete
   void delete(Song song);
 }
 // File: MusicDatabase.java
  @Database(entities = {Song.class})
 public abstract class MusicDatabase extends RoomDatabase {
   public abstract SongDao songDao();
 }
 
You can create an instance of MusicDatabase as follows:
 MusicDatabase db = Room
     .databaseBuilder(getApplicationContext(), MusicDatabase.class, "database-name")
     .build();
 
Since Room verifies your queries at compile time, it also detects information about which tables are accessed by the query or what columns are present in the response.

You can observe a particular table for changes using the InvalidationTracker class which you can acquire via RoomDatabase.getInvalidationTracker.

For convenience, Room allows you to return LiveData from Query methods. It will automatically observe the related tables as long as the LiveData has active observers.

 // This live data will automatically dispatch changes as the database changes.
  @Query("SELECT * FROM song ORDER BY name LIMIT 5")
 LiveData<Song> loadFirstFiveSongs();
 

You can also return arbitrary data objects from your query results as long as the fields in the object match the list of columns in the query response. This makes it very easy to write applications that drive the UI from persistent storage.

 class IdAndSongHeader {
   int id;
    @ColumnInfo(name = "header")
   String header;
 }
 // DAO
  @Query("SELECT id, name || '-' || release_year AS header FROM song")
 public IdAndSongHeader[] loadSongHeaders();
 
If there is a mismatch between the query result and the POJO, Room will print a warning during compilation.

Please see the documentation of individual classes for details.

Interfaces

RoomDatabase.QueryCallbackCallback interface for when SQLite queries are executed.

Classes

DatabaseConfigurationConfiguration class for a RoomDatabase.
EntityDeletionOrUpdateAdapter<T>Implementations of this class knows how to delete or update a particular entity.
EntityInsertionAdapter<T>Implementations of this class knows how to insert a particular entity.
FtsOptionsAvailable option values that can be used with Fts3 & Fts4.
InvalidationTrackerInvalidationTracker keeps a list of tables modified by queries and notifies its callbacks about these tables.
InvalidationTracker.ObserverAn observer that can listen for changes in the database.
MultiInstanceInvalidationServiceA for remote invalidation among multiple InvalidationTracker instances.
RoomUtility class for Room.
RoomDatabaseBase class for all Room databases.
RoomDatabase.Builder<T>Builder for RoomDatabase.
RoomDatabase.CallbackCallback for RoomDatabase.
RoomDatabase.MigrationContainerA container to hold migrations.
RoomDatabase.PrepackagedDatabaseCallbackCallback for RoomDatabase.Builder.createFromAsset(String), RoomDatabase.Builder.createFromFile(File) and RoomDatabase.Builder.createFromInputStream(Callable)
RoomMasterTableSchema information about Room's master table.
RoomOpenHelperAn open helper that holds a reference to the configuration until the database is opened.
RoomOpenHelper.Delegate
RoomOpenHelper.ValidationResult
RoomSQLiteQueryThis class is used as an intermediate place to keep binding arguments so that we can run Cursor queries with correct types rather than passing everything as a string.
RoomWarningsThe list of warnings that are produced by Room.
RxRoomHelper class to add RxJava2 support to Room.
SharedSQLiteStatementRepresents a prepared SQLite state that can be re-used multiple times.

Enums

FtsOptions.MatchInfo
FtsOptions.Order
RoomDatabase.JournalModeJournal modes for SQLite database.

Annotation Types

ColumnInfoAllows specific customization about the column associated with this field.
ColumnInfo.Collate
ColumnInfo.SQLiteTypeAffinityThe SQLite column type constants that can be used in ColumnInfo.typeAffinity()
DaoMarks the class as a Data Access Object.
DatabaseMarks a class as a RoomDatabase.
DatabaseViewMarks a class as an SQLite view.
DeleteMarks a method in a Dao annotated class as a delete method.
EmbeddedMarks a field of an Entity or POJO to allow nested fields (i.e.
EntityMarks a class as an entity.
ExperimentalRoomApiAPIs marked with ExperimentalRoomApi are experimental and may change.
ForeignKeyDeclares a foreign key on another Entity.
ForeignKey.ActionConstants definition for values that can be used in ForeignKey.onDelete() and ForeignKey.onUpdate().
Fts3Marks an Entity annotated class as a FTS3 entity.
Fts4Marks an Entity annotated class as a FTS4 entity.
IgnoreIgnores the marked element from Room's processing logic.
IndexDeclares an index on an Entity.
InsertMarks a method in a Dao annotated class as an insert method.
JunctionDeclares a junction to be used for joining a relationship.
OnConflictStrategySet of conflict handling strategies for various Dao methods.
PrimaryKeyMarks a field in an Entity as the primary key.
ProvidedTypeConverterMarks a class as a type converter that will be provided to Room at runtime.
QueryMarks a method in a Dao annotated class as a query method.
RawQueryMarks a method in a Dao annotated class as a raw query method where you can pass the query as a SupportSQLiteQuery.
RelationA convenience annotation which can be used in a POJO to automatically fetch relation entities.
RewriteQueriesToDropUnusedColumnsWhen present, RewriteQueriesToDropUnusedColumns annotation will cause Room to rewrite your Query methods such that only the columns that are used in the response are queried from the database.
SkipQueryVerificationSkips database verification for the annotated element.
TransactionMarks a method in a Dao class as a transaction method.
TypeConverterMarks a method as a type converter.
TypeConvertersSpecifies additional type converters that Room can use.
UpdateMarks a method in a Dao annotated class as an update method.