Database

public abstract @interface Database
implements Annotation

androidx.room.Database


Marks a class as a RoomDatabase.

The class should be an abstract class and extend RoomDatabase.

You can receive an implementation of the class via Room.databaseBuilder or Room.inMemoryDatabaseBuilder.

 // Song and Album are classes annotated with @Entity.
 @Database(version = 1, entities = {Song.class, Album.class})
 abstract class MusicDatabase extends RoomDatabase {
   // SongDao is a class annotated with @Dao.
   abstract public SongDao getSongDao();
   // AlbumDao is a class annotated with @Dao.
   abstract public ArtistDao getArtistDao();
   // SongAlbumDao is a class annotated with @Dao.
   abstract public SongAlbumDao getSongAlbumDao();
 }
 
The example above defines a class that has 2 tables and 3 DAO classes that are used to access it. There is no limit on the number of Entity or Dao classes but they must be unique within the Database.

Instead of running queries on the database directly, you are highly recommended to create Dao classes. Using Dao classes will allow you to abstract the database communication in a more logical layer which will be much easier to mock in tests (compared to running direct SQL queries). It also automatically does the conversion from Cursor to your application data classes so you don't need to deal with lower level database APIs for most of your data access.

Room also verifies all of your queries in Dao classes while the application is being compiled so that if there is a problem in one of the queries, you will be notified instantly.

To automatically generate a migration between two versions of the database, assuming you have the relevant schema files, you are recommended to use AutoMigration annotations. Note that if an autoMigration is defined in a database, exportSchema must be true.

Summary

Public methods

AutoMigration[] autoMigrations()

List of AutoMigrations that can be performed on this Database.

Class[]<?> entities()

The list of entities included in the database.

boolean exportSchema()

You can set the annotation processor argument (room.schemaLocation) to tell Room to export the database schema into a folder.

int version()

The database version.

Class[]<?> views()

The list of database views included in the database.

Inherited methods

Public methods

autoMigrations

public AutoMigration[] autoMigrations ()

List of AutoMigrations that can be performed on this Database. See AutoMigration for example code usage. For more complicated cases not covered by AutoMigration, runtime de