android.arch.persistence.room
Rather than hiding the detail 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 extendsRoomDatabase
. At runtime, you can acquire an instance of it viaRoom.databaseBuilder
orRoom.inMemoryDatabaseBuilder
.This 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 eachEntity
, a database table is created to hold the items. The Entity class must be referenced in theDatabase#entities
array. Each field of the Entity (and its super class) is persisted in the database unless it is denoted otherwise (seeEntity
docs for details).Dao
: This annotation marks a class or interface as a Data Access Object. Data access objects are the main component of Room that are responsible for defining the methods that access the database. The class that is annotated withDatabase
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.
// File: User.java @Entity public class User { @PrimaryKey private int uid; private String name; @ColumnInfo(name = "last_name") private String lastName; // getters and setters are ignored for brevity but they are required for Room to work. } // File: UserDao.java @Dao public interface UserDao { @Query("SELECT * FROM user") List<User> loadAll(); @Query("SELECT * FROM user WHERE uid IN (:userIds)") List<User> loadAllByUserId(int... userIds); @Query("SELECT * FROM user where name LIKE :first AND last_name LIKE :last LIMIT 1") User loadOneByNameAndLastName(String first, String last); @Insert void insertAll(User... users); @Delete void delete(User user); } // File: AppDatabase.java @Database(entities = {User.java}) public abstract class AppDatabase extends RoomDatabase { public abstract UserDao userDao(); }You can create an instance of
AppDatabase
as follows:
AppDatabase db = Room .databaseBuilder(getApplicationContext(), AppDatabase.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 user ORDER BY name LIMIT 5") LiveData<User> loadFirstFiveUsers();
You can also return arbitrary Java 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 IdAndFullName { public int uid; @ColumnInfo(name = "full_name") public String fullName; } // DAO @Query("SELECT uid, name || lastName as full_name FROM user") public IdAndFullName[] loadFullNames();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.
Annotations
ColumnInfo | Allows specific customization about the column associated with this field. |
ColumnInfo.Collate | |
ColumnInfo.SQLiteTypeAffinity |
The SQLite column type constants that can be used in typeAffinity()
|
Dao | Marks the class as a Data Access Object. |
Database | Marks a class as a RoomDatabase. |
Delete |
Marks a method in a Dao annotated class as a delete method.
|
Embedded |
Can be used as an annotation on a field of an Entity or Pojo to signal that
nested fields (i.e.
|
Entity | Marks a class as an entity. |
ForeignKey |
Declares a foreign key on another Entity .
|
ForeignKey.Action |
Constants definition for values that can be used in onDelete() and
onUpdate() .
|
Ignore | Ignores the marked element from Room's processing logic. |
Index | Declares an index on an Entity. |
Insert |
Marks a method in a Dao annotated class as an insert method.
|
OnConflictStrategy |
Set of conflict handling strategies for various Dao methods.
|
PrimaryKey |
Marks a field in an Entity as the primary key.
|
Query |
Marks a method in a Dao annotated class as a query method.
|
RawQuery |
Marks a method in a Dao annotated class as a raw query method where you can pass the
query as a SupportSQLiteQuery .
|
Relation | A convenience annotation which can be used in a Pojo to automatically fetch relation entities. |
SkipQueryVerification | Skips database verification for the annotated element. |
Transaction |
Marks a method in a Dao class as a transaction method.
|
TypeConverter | Marks a method as a type converter. |
TypeConverters | Specifies additional type converters that Room can use. |
Update |
Marks a method in a Dao annotated class as an update method.
|
Classes
DatabaseConfiguration |
Configuration class for a RoomDatabase .
|
InvalidationTracker | InvalidationTracker keeps a list of tables modified by queries and notifies its callbacks about these tables. |
InvalidationTracker.Observer | An observer that can listen for changes in the database. |
Room | Utility class for Room. |
RoomDatabase | Base class for all Room databases. |
RoomDatabase.Builder<T extends RoomDatabase> | Builder for RoomDatabase. |
RoomDatabase.Callback |
Callback for RoomDatabase .
|
RoomDatabase.MigrationContainer | A container to hold migrations. |
RoomWarnings | The list of warnings that are produced by Room. |
RxRoom | Helper class to add RxJava2 support to Room. |
Enums
RoomDatabase.JournalMode | Journal modes for SQLite database. |
Exceptions
EmptyResultSetException | Thrown by Room when the query needs to return a result (e.g. |
Annotations
Classes
Enums
Exceptions