dependencies{valroom_version="2.7.2"implementation("androidx.room:room-runtime:$room_version")// If this project uses any Kotlin source, use Kotlin Symbol Processing (KSP)// See Add the KSP plugin to your projectksp("androidx.room:room-compiler:$room_version")// If this project only uses Java source, use the Java annotationProcessor// No additional plugins are necessaryannotationProcessor("androidx.room:room-compiler:$room_version")// optional - Kotlin Extensions and Coroutines support for Roomimplementation("androidx.room:room-ktx:$room_version")// optional - RxJava2 support for Roomimplementation("androidx.room:room-rxjava2:$room_version")// optional - RxJava3 support for Roomimplementation("androidx.room:room-rxjava3:$room_version")// optional - Guava support for Room, including Optional and ListenableFutureimplementation("androidx.room:room-guava:$room_version")// optional - Test helperstestImplementation("androidx.room:room-testing:$room_version")// optional - Paging 3 Integrationimplementation("androidx.room:room-paging:$room_version")}
Groovy
dependencies{defroom_version="2.7.2"implementation"androidx.room:room-runtime:$room_version"// If this project uses any Kotlin source, use Kotlin Symbol Processing (KSP)// See KSP Quickstart to add KSP to your buildksp"androidx.room:room-compiler:$room_version"// If this project only uses Java source, use the Java annotationProcessor// No additional plugins are necessaryannotationProcessor"androidx.room:room-compiler:$room_version"// optional - RxJava2 support for Roomimplementation"androidx.room:room-rxjava2:$room_version"// optional - RxJava3 support for Roomimplementation"androidx.room:room-rxjava3:$room_version"// optional - Guava support for Room, including Optional and ListenableFutureimplementation"androidx.room:room-guava:$room_version"// optional - Test helperstestImplementation"androidx.room:room-testing:$room_version"// optional - Paging 3 Integrationimplementation"androidx.room:room-paging:$room_version"}
以下代码定义了一个名为 UserDao 的 DAO。UserDao 提供了应用的其余部分与 user 表中的数据交互的方法。
Kotlin
@DaointerfaceUserDao{@Query("SELECT * FROM user")fungetAll():List<User>@Query("SELECT * FROM user WHERE uid IN (:userIds)")funloadAllByIds(userIds:IntArray):List<User>@Query("SELECT * FROM user WHERE first_name LIKE :first AND "+"last_name LIKE :last LIMIT 1")funfindByName(first:String,last:String):User@InsertfuninsertAll(varargusers:User)@Deletefundelete(user:User)}
Java
@DaopublicinterfaceUserDao{@Query("SELECT * FROM user")List<User>getAll();@Query("SELECT * FROM user WHERE uid IN (:userIds)")List<User>loadAllByIds(int[]userIds);@Query("SELECT * FROM user WHERE first_name LIKE :first AND "+"last_name LIKE :last LIMIT 1")UserfindByName(Stringfirst,Stringlast);@InsertvoidinsertAll(User...users);@Deletevoiddelete(Useruser);}
[null,null,["最后更新时间 (UTC):2025-08-13。"],[],[],null,["# Save data in a local database using Room\nPart of [Android Jetpack](/jetpack).\n=============================================================================\n\nApps that handle non-trivial amounts of structured data can benefit greatly from\npersisting that data locally. The most common use case is to cache relevant\npieces of data so that when the device cannot access the network, the user can\nstill browse that content while they are offline.\n\nThe Room persistence library provides an abstraction layer over SQLite to allow\nfluent database access while harnessing the full power of SQLite. In particular,\nRoom provides the following benefits:\n\n- Compile-time verification of SQL queries.\n- Convenience annotations that minimize repetitive and error-prone boilerplate code.\n- Streamlined database migration paths.\n\nBecause of these considerations, we highly recommend that you use Room instead\nof [using the SQLite APIs directly](/training/data-storage/sqlite).\n\nSetup\n-----\n\nTo use Room in your app, add the following dependencies to your app's\n`build.gradle` file.\n**Note:** Choose only one of `ksp` or `annotationProcessor`. Don't include both. \n\n### Kotlin\n\n```kotlin\ndependencies {\n val room_version = \"2.7.2\"\n\n implementation(\"androidx.room:room-runtime:$room_version\")\n\n // If this project uses any Kotlin source, use Kotlin Symbol Processing (KSP)\n // See /build/migrate-to-ksp#add-ksp\n ksp(\"androidx.room:room-compiler:$room_version\")\n\n // If this project only uses Java source, use the Java annotationProcessor\n // No additional plugins are necessary\n annotationProcessor(\"androidx.room:room-compiler:$room_version\")\n\n // optional - Kotlin Extensions and Coroutines support for Room\n implementation(\"androidx.room:room-ktx:$room_version\")\n\n // optional - RxJava2 support for Room\n implementation(\"androidx.room:room-rxjava2:$room_version\")\n\n // optional - RxJava3 support for Room\n implementation(\"androidx.room:room-rxjava3:$room_version\")\n\n // optional - Guava support for Room, including Optional and ListenableFuture\n implementation(\"androidx.room:room-guava:$room_version\")\n\n // optional - Test helpers\n testImplementation(\"androidx.room:room-testing:$room_version\")\n\n // optional - Paging 3 Integration\n implementation(\"androidx.room:room-paging:$room_version\")\n}\n```\n\n### Groovy\n\n```groovy\ndependencies {\n def room_version = \"2.7.2\"\n\n implementation \"androidx.room:room-runtime:$room_version\"\n\n // If this project uses any Kotlin source, use Kotlin Symbol Processing (KSP)\n // See https://kotlinlang.org/docs/ksp-quickstart.html to add KSP to your build\n ksp \"androidx.room:room-compiler:$room_version\"\n\n // If this project only uses Java source, use the Java annotationProcessor\n // No additional plugins are necessary\n annotationProcessor \"androidx.room:room-compiler:$room_version\"\n\n // optional - RxJava2 support for Room\n implementation \"androidx.room:room-rxjava2:$room_version\"\n\n // optional - RxJava3 support for Room\n implementation \"androidx.room:room-rxjava3:$room_version\"\n\n // optional - Guava support for Room, including Optional and ListenableFuture\n implementation \"androidx.room:room-guava:$room_version\"\n\n // optional - Test helpers\n testImplementation \"androidx.room:room-testing:$room_version\"\n\n // optional - Paging 3 Integration\n implementation \"androidx.room:room-paging:$room_version\"\n}\n```\n\nPrimary components\n------------------\n\nThere are three major components in Room:\n\n- The [database class](/reference/kotlin/androidx/room/Database) that holds the database and serves as the main access point for the underlying connection to your app's persisted data.\n- [Data entities](/training/data-storage/room/defining-data) that represent tables in your app's database.\n- [Data access objects (DAOs)](/training/data-storage/room/accessing-data) that provide methods that your app can use to query, update, insert, and delete data in the database.\n\nThe database class provides your app with instances of the DAOs associated with\nthat database. In turn, the app can use the DAOs to retrieve data from the\ndatabase as instances of the associated data entity objects. The app can also\nuse the defined data entities to update rows from the corresponding tables, or\nto create new rows for insertion. Figure 1 illustrates the relationship between\nthe different components of Room.\n**Figure 1.** Diagram of Room library architecture.\n\nSample implementation\n---------------------\n\nThis section presents an example implementation of a Room database with a single\ndata entity and a single DAO.\n\n### Data entity\n\nThe following code defines a `User` data entity. Each instance of `User`\nrepresents a row in a `user` table in the app's database. \n\n### Kotlin\n\n```kotlin\n@Entity\ndata class User(\n @PrimaryKey val uid: Int,\n @ColumnInfo(name = \"first_name\") val firstName: String?,\n @ColumnInfo(name = \"last_name\") val lastName: String?\n)\n```\n\n### Java\n\n```java\n@Entity\npublic class User {\n @PrimaryKey\n public int uid;\n\n @ColumnInfo(name = \"first_name\")\n public String firstName;\n\n @ColumnInfo(name = \"last_name\")\n public String lastName;\n}\n```\n\nTo learn more about data entities in Room, see [Defining data using Room\nentities](/training/data-storage/room/defining-data).\n\n### Data access object (DAO)\n\nThe following code defines a DAO called `UserDao`. `UserDao` provides the\nmethods that the rest of the app uses to interact with data in the `user` table. \n\n### Kotlin\n\n```kotlin\n@Dao\ninterface UserDao {\n @Query(\"SELECT * FROM user\")\n fun getAll(): List\u003cUser\u003e\n\n @Query(\"SELECT * FROM user WHERE uid IN (:userIds)\")\n fun loadAllByIds(userIds: IntArray): List\u003cUser\u003e\n\n @Query(\"SELECT * FROM user WHERE first_name LIKE :first AND \" +\n \"last_name LIKE :last LIMIT 1\")\n fun findByName(first: String, last: String): User\n\n @Insert\n fun insertAll(vararg users: User)\n\n @Delete\n fun delete(user: User)\n}\n```\n\n### Java\n\n```java\n@Dao\npublic interface UserDao {\n @Query(\"SELECT * FROM user\")\n List\u003cUser\u003e getAll();\n\n @Query(\"SELECT * FROM user WHERE uid IN (:userIds)\")\n List\u003cUser\u003e loadAllByIds(int[] userIds);\n\n @Query(\"SELECT * FROM user WHERE first_name LIKE :first AND \" +\n \"last_name LIKE :last LIMIT 1\")\n User findByName(String first, String last);\n\n @Insert\n void insertAll(User... users);\n\n @Delete\n void delete(User user);\n}\n```\n\nTo learn more about DAOs, see [Accessing data using Room\nDAOs](/training/data-storage/room/accessing-data).\n\n### Database\n\nThe following code defines an `AppDatabase` class to hold the database.\n`AppDatabase` defines the database configuration and serves as the app's main\naccess point to the persisted data. The database class must satisfy the\nfollowing conditions:\n\n- The class must be annotated with a [`@Database`](/reference/kotlin/androidx/room/Database) annotation that includes an [`entities`](/reference/kotlin/androidx/room/Database#entities) array that lists all of the data entities associated with the database.\n- The class must be an abstract class that extends [`RoomDatabase`](/reference/kotlin/androidx/room/RoomDatabase).\n- For each DAO class that is associated with the database, the database class must define an abstract method that has zero arguments and returns an instance of the DAO class.\n\n### Kotlin\n\n```kotlin\n@Database(entities = [User::class], version = 1)\nabstract class AppDatabase : RoomDatabase() {\n abstract fun userDao(): UserDao\n}\n```\n\n### Java\n\n```java\n@Database(entities = {User.class}, version = 1)\npublic abstract class AppDatabase extends RoomDatabase {\n public abstract UserDao userDao();\n}\n``` \n**Note:** If your app runs in a single process, you should follow the\nsingleton design pattern when instantiating an `AppDatabase`\nobject. Each `RoomDatabase` instance is fairly expensive, and you\nrarely need access to multiple instances within a single process.\n\nIf your app runs in multiple processes, include\n`enableMultiInstanceInvalidation()` in your database builder\ninvocation. That way, when you have an instance of `AppDatabase`\nin each process, you can invalidate the shared database file in one process,\nand this invalidation automatically propagates to the instances of\n`AppDatabase` within other processes.\n\n### Usage\n\nAfter you have defined the data entity, the DAO, and the database object, you\ncan use the following code to create an instance of the database: \n\n### Kotlin\n\n```kotlin\nval db = Room.databaseBuilder(\n applicationContext,\n AppDatabase::class.java, \"database-name\"\n ).build()\n```\n\n### Java\n\n```java\nAppDatabase db = Room.databaseBuilder(getApplicationContext(),\n AppDatabase.class, \"database-name\").build();\n```\n\nYou can then use the abstract methods from the `AppDatabase` to get an instance\nof the DAO. In turn, you can use the methods from the DAO instance to interact\nwith the database: \n\n### Kotlin\n\n```kotlin\nval userDao = db.userDao()\nval users: List\u003cUser\u003e = userDao.getAll()\n```\n\n### Java\n\n```java\nUserDao userDao = db.userDao();\nList\u003cUser\u003e users = userDao.getAll();\n```\n\nAdditional resources\n--------------------\n\nTo learn more about Room, see the following additional resources:\n\n### Samples\n\n### Codelabs\n\n- Android Room with a View [(Java)](/codelabs/android-room-with-a-view) [(Kotlin)](/codelabs/android-room-with-a-view-kotlin)\n\n### Blogs\n\n- [7 Pro-tips for\n Room](https://medium.com/androiddevelopers/7-pro-tips-for-room-fbadea4bfbd1)\n- [Incrementally migrate from SQLite to\n Room](https://medium.com/androiddevelopers/incrementally-migrate-from-sqlite-to-room-66c2f655b377)"]]