Room

The Room persistence library provides an abstraction layer over SQLite to allow for more robust database access while harnessing the full power of SQLite. See the reference docs for more information.

Declaring dependencies

To add a dependency on Room, you must add the Google Maven repository to your project. Read Google's Maven repository for more information.

Dependencies for Room include testing Room migrations and Room RxJava

Add the dependencies for the artifacts you need in the build.gradle file for your app or module:

dependencies {
  def room_version = "2.2.0-rc01"

  implementation "androidx.room:room-runtime:$room_version"
  annotationProcessor "androidx.room:room-compiler:$room_version" // For Kotlin use kapt instead of annotationProcessor

  // optional - Kotlin Extensions and Coroutines support for Room
  implementation "androidx.room:room-ktx:$room_version"

  // optional - RxJava support for Room
  implementation "androidx.room:room-rxjava2:$room_version"

  // optional - Guava support for Room, including Optional and ListenableFuture
  implementation "androidx.room:room-guava:$room_version"

  // Test helpers
  testImplementation "androidx.room:room-testing:$room_version"
}

For information on using Kotlin extensions, see the ktx documentation.

For more information about dependencies, see Add Build Dependencies.

Configuring Compiler Options

Room has the following annotation processor options:

  • room.schemaLocation: Configures and enables exporting database schemas into JSON files in the given directory. See Room Migrations for more information.
  • room.incremental: Enables Gradle incremental annotation proccesor.
  • room.expandProjection: Configures Room to rewrite queries such that their top star projection is expanded to only contain the columns defined in the DAO method return type.

An example of how these options can be configured are shown in the following code snippet:

android {
    ...
    defaultConfig {
        ...
        javaCompileOptions {
            annotationProcessorOptions {
                arguments = [
                    "room.schemaLocation":"$projectDir/schemas".toString(),
                    "room.incremental":"true",
                    "room.expandProjection":"true"]
            }
        }
    }
}

Version 2.2.0-rc01

September 5, 2019

androidx.room:room:2.2.0-rc01 is released. The commits included in this version can be found here.

No public changes since Room 2.2.0-beta01.

Version 2.2.0-beta01

August 22, 2019

androidx.room:room-*:2.2.0-beta01 is released. The commits included in this version can be found here.

Bug fixes

  • Fixed a bug where a Coroutine Flow query would stop reemitting new values after a certain time. (b/139175786)
  • Fixed a bug where Room would not accept a legacy schema hash code while opening a database that had not gone a migration since Room 1.0, causing a runtime crash due to invalid schema. (b/139306173)

Version 2.2.0-alpha02

August 7, 2019

androidx.room:room-*:2.2.0-alpha02 is released. The commits included in this version can be found here.

New Features

  • Coroutines Flow: @Query DAO methods can now be of return type Flow<T>. The returned Flow will re-emit a new set of values if the observing tables in the query are invalidated. Declaring a DAO function with a Channel<T> return type is an error, Room instead encourages you to use Flow and then use the neighboring functions to convert the Flow into a Channel. b/130428884
  • Expanding Projections: A new experimental compiler option room.expandProjection was added that causes Room to rewrite a query with a star projection to only contain the columns in the returning type POJO. For example, for a DAO method with @Query("SELECT * FROM Song") that returns a POJO named SongIdAndTitle with only two fields. Then Room will rewrite the query to SELECT id, title FROM Song such that the minimum set of columns to satisfy the return type are fetched. This essentially eliminates the CURSOR_MISMATCH warning that is presented when the query returns extra columns that do not match any field in the returning POJO type.
  • onDestructiveMigrate is a new callback API added to RoomDatabase.Callback for when Room destructively migrates a database. b/79962330

Bug Fixes

  • Fixed a bug where Room would generate incorrect code using a method as field setter when the field is protected. b/136194628
  • Fixed a bug that caused the InvalidationTracker to throw a NPE in a second process when multi-instance invalidation was enabled and the invalidation Service was killed. b/137454915
  • Fixed a bug where Room would not correctly identify the return type of an inherited suspend function annotated with @RawQuery. b/137878827
  • Updated the generated code for @Relation when the relating key is of type BLOB to use a ByteBuffer that is comparable. b/137881998
  • Fixed a bug where Room would complain about missing setters on POJOs used as partial entity parameters of @Insert, @Update and @Delete. b/138664463
  • Fixed a bug where Room would complain about missing getters & setters for an ignored column via @Entity when the entity class was used in certain DAO methods. b/138238182
  • Fixed a bug where Room would not correctly convert named binding args to positional args causing a runtime exception when executing a query with re-used parameters. b/137254857

Version 2.2.0-alpha01

July 10, 2019

New Features

  • Pre-packaged Database: Two new APIs in RoomDatabase.Builder are now available for creating a RoomDatabase given an already populated database file. createFromAsset() is for when the pre-populated database file is in the assets folder of the APK, while createFromFile() is for when the file is in an arbitrary location. The usages of these API change the behaviour of destructive migrations such that during a fallback migration, Room will try to re-copy the pre-populated database if available, otherwise it fallbacks to just dropping and re-creating all tables. b/62185732
  • Schema Default Values: @ColumnInfo now has a new property defaultValue that can be used to specify the default value of a column. Default values are part of a database schema and will be validated during migrations if specified. b/64088772

    Note: If your database schema already has default values, such as those added via ALTER TABLE x ADD COLUMN y INTEGER NOTNULL DEFAULT z, and you decide to define default values via @ColumnInfo to the same columns, then you might need to provide a migration to validate the unaccounted default values. See Room Migrations for more information.

  • Many-to-Many Relations: @Relation now has a new property associateBy, that takes in a new annotation @Junction, used to declare a relation that needs to be satisfied via a junction table (also known as a join table). b/69201917
  • One-to-One Relations: The restriction in POJO fields annotated with @Relation to be of type List or Set has been lifted, effectively allowing single-value relations to be represented. b/62905145
  • Target Entity: The DAO annnotations @Insert, @Update and @Delete now has a new property targetEntity, that allows specifying the target table the DAO method is meant to act on. This allows for the parameters of those DAO methods to be arbitrary POJOs which will be interpreted as partial entities. In practice, this allows partial inserts, deletes and updates. b/127549506
  • Gradle Incremental Annotation Processor: Room is now a Gradle isolating annotation processor and incrementability can be enabled via the processor option room.incremental. See Room Compiler Options for more information. If you encounter any issues please file a bug here. We plan to enable incrementability by default in a future, stable version. b/112110217

Bug Fixes

  • Room will no longer propagate the EmptySetResultException to the global error handler when the Rx stream of a query has been disposed before the query is complete. b/130257475
  • Fixed a bug where Room would show an incorrect error message when a suspend DAO function annotated with @RawQuery didn't have a return type. b/134303897
  • Room will no longer generate DAO adapters with raw types. b/135747255

Version 2.1.0

June 13, 2019

Room 2.1.0 is released with no changes from 2.1.0-rc01. The commits included in the version can be found here.

Important changes since 2.0.0

  • FTS: Room now supports entities with a mapping FTS3 or FTS4 table. Classes annotated with @Entity can now be additionally annotated with @Fts3 or @Fts4 to declare a class with a mapping full-text search table. FTS options for further customization are available via the annotation’s methods.
  • Views: Room now supports declaring a class as a stored query, also known as a view, using the @DatabaseView annotation.
  • Couroutines: DAO methods can now be suspend functions. Include room-ktx in your dependencies to take advantage of this functionality. The ktx artifact also provides the extension function RoomDatabase.withTransaction for performing database transactions within a coroutine.
  • Auto Value: Room now supports declaring AutoValue annotated classes as entities and POJOs. The Room annotations @PrimaryKey, @ColumnInfo, @Embedded and @Relation can now be declared in an auto value annotated class’s abstract methods. Note that these annotation must also be accompanied by @CopyAnnotations for Room to properly understand them.
  • Additional Async Support: DAO methods annotated with @Insert, @Delete or @Update, along with @Query containing INSERT, DELETE or UPDATE statements, now support Rx return types Completable, Single, Maybe, and Guava's return type ListenableFuture, and they can also be suspend functions.
  • enableMultiInstanceInvalidation is a new API in RoomDatabase.Builder to enable invalidation across multiple instances of RoomDatabase using the same database file.
  • fallbackToDestructiveMigrationOnDowngrade is a new API in RoomDatabase.Builder to automatically re-create the database if a downgrade happens.
  • ignoredColumns is a new API in the @Entity annotation that can be used to list ignored fields by name.
  • Room will now properly use Kotlin’s primary constructor in data classes avoiding the need to declare the properties as vars.

Version 2.1.0-rc01

May 29, 2019

Bug Fixes

  • Fixed a Room initialization error that might occur due to an already setup temp_store configuration. b/132602198
  • Fixed a double quote usage warning for users with SQLite 3.27.0 and above. b/131712640
  • Fixed a bug where the InvalidationTracker would cause a crash when multiple invalidation checks would occur in parallel. b/133457594

Version 2.1.0-beta01

May 7, 2019

androidx.room 2.1.0-beta01 is released with no changes from 2.1.0-alpha07. The commits included in this version can be found here.

Version 2.1.0-alpha07

April 25, 2019

API / Behavior Changes

  • The extension function RoomDatabase.withTransaction has been changed to no longer take a function block with a CoroutineScope as receiver. This prevents skipping the additional coroutineScope { } wrapper required to run things in the transaction block concurrently.

Bug Fixes

  • Fixed a bug where Room would fail to match a TypeConverter for a Kotlin DAO function containing a parameter of Collection type. b/122066791

Version 2.1.0-alpha06

March 22, 2019

API / Behavior Changes

  • Async transaction queries are now serialized such that Room will not use more than one thread for executing database transactions. RoomDatabase.Builder.setTransactionExecutor(Executor) was added to allow configuring the executor to be used for transactions.
  • RoomDatabase.runInTransaction(Callable) will no longer wrap checked exceptions into RuntimeExceptions. b/128623748

Bug Fixes

  • Fixed a bug where the invalidation tracker would stop observing a content table if observers for both the content table and an external content FTS table were added. b/128508917
  • Updated Room's SQLite grammar to match SQLite 3.24.0. b/110883668

Version 2.1.0-alpha05

March 13, 2019

New Features

  • The extension function RoomDatabase.withTransaction allows you to safely perform database transactions within a coroutine. Room extensions functions along with coroutines support are available in the room-ktx artifact.
  • Non-abstract DAO methods annotated with @Transaction can now be suspend functions. b/120241587

API / Behavior Changes

  • The artifact room-coroutines has been renamed to room-ktx following the same naming as other androidx artifacts.
  • beginTransaction, setTransactionSuccessful and endTransaction in RoomDatabase have been deprecated in favor of runInTransaction and the room-ktx extension function withTransaction.

Bug Fixes

  • Fixed a bug where tokenizer arguments were being dropped if the tokenizer used was SIMPLE. b/125427014
  • Fixed a bug where Room would fail to correctly identify suspending functions with parameters whos type were an inner class. b/123767877
  • Fixed a bug where deferred @Query DAO method with INSERT, UPDATE or DELETE statements were eagerly preparing the query in the main thread. b/123695593
  • Fixed various bugs where Room would generate incorrect code for certain suspend functions. b/123466702 and b/123457323
  • Fixed a bug where deprecated usage of methods were not being correctly suppressed in generated code. b/117602586
  • Updated Room dependency of androidx.sqlite to 1.0.2 which contain fixes for correctly handling corrupted databases. b/124476912

Known Issues

  • Room 2.1.0-alpha05 depends on the kotlinx-metadata-jvm artifact which is not currently available in Maven Central (KT-27991). This dependency can be resolved by adding maven { url "https://kotlin.bintray.com/kotlinx/" } to your project repositories.

Version 2.1.0-alpha04

January 25, 2019

New Features

  • DAO methods annotated with @Query containing INSERT, UPDATE or DELETE statements can now return async types Single, Mayble, Completable and ListenableFuture. Additionally they can also be suspend functions. b/120227284

API / Behavior Changes

  • Room will now throw an error if a non-abstract DAO method annotated with @Transaction returns an async type such as Single, Mayble, Completable, LiveData or ListenableFuture. Since transactions are thread confined it is currently impossible for Room to begin and end a transaction around a function that may peform queries in different threads. b/120109336
  • OnConflictStrategy.FAIL and OnConflictStrategy.ROLLBACK have been @Deprecated since they do not behave as intended with Android's current SQLite bindings. b/117266738

Bug Fixes

  • Fixed a bug where Room wouldn't correctly use the TypeConverter of a return type if the DAO method was a suspend function. b/122988159
  • Fixed a bug where Room would incorrectly identify inherited suspend functions as non-suspending. b/122902595
  • Fixed a bug where Room would generate incorrect code when an @Embedded field was in a parent class and used in multiple child classes. b/121099048
  • Fixed an issue where the database would deadlock when invoking DAO suspend functions between a beginTransaction() and endTransaction(). b/120854786

Version 2.1.0-alpha03

December 4, 2018

API Changes

  • The FTS tokenizer in @Fts3/@Fts4 now takes a String instead of an Enum. This allows custom tokenizers to be used by Room. Built-in tokenizers are still defined in FtsOptions as string constants. b/119234881

New Features

  • Couroutines: DAO methods can now be suspend functions. To support suspend functions in Room a new artifact has been released, room-coroutines. b/69474692
  • DAO methods annotated with @Insert, @Delete or @Update now support ListenableFuture as return type. b/119418331

Bug Fixes

  • Fixed a bug where Room would incorrectly attempt to find a constructor with columns in the ignoredColumns property of @Entity. b/119830714
  • Fixed a bug where Room would not mark DAO method parameters as final in their generated implementation. b/118015483
  • Fixed a bug where Room's processor would crash when reporting an error on a query with special symbols. b/119520136
  • Fixed a bug where Room would decline other various Collection implementations as arguments of an IN expression. b/119884035
  • Fixed a bug where LiveData returned from Room would get garbage collected when observed forever causing it to no longer emit new data. b/74477406
  • Updated RoomDatabase's close lock to reduce lock contention. b/117900450

Version 2.1.0-alpha02

October 30, 2018

New Features

  • Added support for referencing a @DatabaseView in a @Relation. b/117680932

Bug Fixes

  • Fixed a bug where Room would perform disk I/O in the main thread when subscribing and disposing from an Rx return type. b/117201279
  • Fixed a bug where Room would fail to find an appropriate type converter for a field in a Kotlin entity class. b/111404868
  • Fixed a bug where Room would generate incorrect code for a DAO interface implementation containing a Kotlin default method that has no arguments. b/117527454
  • Updated Room's SQLite grammar parser, fixing a performance issue that would cause long build times. b/117401230

Version 2.1.0-alpha01

October 8, 2018

New Features

  • FTS: Room now supports entities with a mapping FTS3 or FTS4 table. Classes annotated with @Entity can now be additionally annotated with @Fts3 or @Fts4 to declare a class with a mapping full-text search table. FTS options for further customization are available via the annotation’s methods. b/62356416
  • Views: Room now supports declaring a class as a stored query, also known as a view using the @DatabaseView annotation. b/67033276
  • Auto Value: Room now supports declaring AutoValue annotated classes as entities and POJOs. The Room annotations @PrimaryKey, @ColumnInfo, @Embedded and @Relation can now be declared in an auto value annotated class’ abstract methods. Note that these annotation must also be accompanied by @CopyAnnotations for Room to properly understand them. b/62408420
  • Additional Rx Return Types Support: DAO methods annotated with @Insert, @Delete or @Update now support Rx return types Completable, Single<T> and Maybe<T>. b/63317956
  • Immutable Types with @Relation: Room previously required @Relation annotated fields to be settable but now they can be constructor parameters.
  • enableMultiInstanceInvalidation: Is a new API in RoomDatabase.Builder to enable invalidation across multiple instances of RoomDatabase using the same database file. This multi-instance invalidation mechanism also works across multiple processes. b/62334005
  • fallbackToDestructiveMigrationOnDowngrade: Is a new API in RoomDatabase.Builder to automatically re-create the database if a downgrade happens. b/110416954
  • ignoredColumns: Is a new API in the @Entity annotation that can be used to list ignored fields by name. Useful for ignoring inherited fields on an entity. b/63522075

API / Behavior Changes

  • mCallback and mDatabase in RoomDatabase are now @Deprecated and will be removed in the next major version of Room. b/76109329

Bug Fixes

  • Fixed two issues where Room wouldn’t properly recover from a corrupted database or a bad migration during initialization. b/111504749 and b/111519144
  • Room will now properly use Kotlin’s primary constructor in data classes avoiding the need to declare the fields as vars. b/105769985

Version 2.0.0-beta01

July 2, 2018

API / Behavior Changes

  • Added RoomDatabase.Builder.setQueryExecutor() to allow customization of where queries are run
  • Added RxJava2 Observable support
  • Generated DAO and Database implementations are now final

Bug Fixes

  • Specify class/field name in "cannot find getter for field" error b/73334503
  • Fixed RoomOpenHelper backwards compatibility with older versions of Room b/110197391

Pre-AndroidX Dependencies

For the pre-AndroidX versions of Room, include these dependencies:

dependencies {
    def room_version = "1.1.1"

    implementation "android.arch.persistence.room:runtime:$room_version"
    annotationProcessor "android.arch.persistence.room:compiler:$room_version" // For Kotlin use kapt instead of annotationProcessor

    // optional - RxJava support for Room
    implementation "android.arch.persistence.room:rxjava2:$room_version"

    // optional - Guava support for Room, including Optional and ListenableFuture
    implementation "android.arch.persistence.room:guava:$room_version"

    // Test helpers
    testImplementation "android.arch.persistence.room:testing:$room_version"
}

Version 1.1.1

June 19, 2018

Room 1.1.1 is identical to Room 1.1.1-rc1.

Version 1.1.1-rc1

May 16, 2018 We highly recommend using Room 1.1.1-rc1 instead of 1.1.0 if you are using migrations.

Fixed a bug where Room would not handle post migration initialization properly b/79362399

Version 1.1.0-beta3

April 19, 2018

Bug Fixes

  • Fix compilation error when a Kotlin POJO references a relation entity that was defined in Java b/78199923

Version 1.1.0-beta2

April 5, 2018

Bug Fixes

  • Fixed a critical bug in Room's Rx Single and Maybe implementations where it would recycle the query ahead of time, causing problems if you add more than 1 observer to the returned Single or Maybe instancces. b/76031240

  • [RoomDatabase.clearAllTables][ref-clearAllTables] will not VACUUM the database if it is called inside a transaction. b/77235565

Version 1.1.0-beta1

March 21, 2018

API Changes

  • Based on API Review feedback, @RawQuery does not accept passing a String as the query parameter anymore. You need to use [SupportSQLiteQuery][ref-SupportSQLiteQuery]. (see [SimpleSQLiteQuery][ref-SimpleSQLiteQuery] to easily create an instance of [SupportSQLiteQuery][ref-SupportSQLiteQuery] with argument support).
  • RoomDatabase.Builder's [fallbackToDestructiveMigrationFrom][ref-fallbackToDestructiveMigrationFrom] method now accepts vararg int instead of vararg Integer.

Bug Fixes

  • [RoomDatabase.clearAllTables][ref-clearAllTables] now tries to return space back to the operating system by setting a WAL checkpoint and VACUUMing the database.
  • [@RawQuery][ref-RawQuery] now accepts any Pojo for the observedEntities property as long as the Pojo references to one or more entities via its Embedded fields or Relations. b/74041772
  • Paging: Room’s DataSource implementation now correctly handles multi-table dependencies (such as relations, and joins). Previously these would fail to trigger new results, or could fail to compile. b/74128314

Version 1.1.0-alpha1

January 22, 2018

New Features

  • RawQuery: This new API allows @Dao methods to receive the SQL as a query parameter b/62103290, b/71458963
  • fallBackToDestructiveMigrationsFrom: This new API in RoomDatabase.Builder allows for finer grained control over from which starting schema versions destructive migrations are allowed (as compared to fallbackToDestructiveMigration) b/64989640
  • Room now only supports newer Paging APIs (alpha-4+), dropping support for the deprecated LivePagedListProvider. To use the new Room alpha, you’ll need to use paging alpha-4 or higher, and switch from LivePagedListProvider to LivePagedListBuilder if you haven’t already.

Bug Fixes

  • Improved support for Kotlin Kapt types. b/69164099
  • Order of fields do not invalidate schema anymore. b/64290754