앱에서 Room을 사용하려면 앱의 build.gradle 파일에 다음 종속 항목을 추가합니다.
Kotlin
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"}
기본 구성요소
Room에는 다음 3가지 주요 구성요소가 있습니다.
데이터베이스 클래스: 데이터베이스를 보유하고 앱의 영구 데이터와의 기본 연결을 위한 기본 액세스 포인트 역할을 합니다.
데이터 액세스 객체(DAO): 앱이 데이터베이스의 데이터를 쿼리, 업데이트, 삽입, 삭제하는 데 사용할 수 있는 메서드를 제공합니다.
데이터베이스 클래스는 데이터베이스와 연결된 DAO 인스턴스를 앱에 제공합니다. 그러면 앱은 DAO를 사용하여 데이터베이스의 데이터를 연결된 데이터 항목 객체의 인스턴스로 검색할 수 있게 됩니다. 앱은 정의된 데이터 항목을 사용하여 상응하는 테이블의 행을 업데이트하거나 삽입할 새 행을 만들 수도 있습니다. 그림 1은 다양한 Room 구성요소 간 관계를 보여줍니다.
그림 1. Room 라이브러리 아키텍처 다이어그램
샘플 구현
이 섹션에서는 단일 데이터 항목과 단일 DAO가 있는 Room 데이터베이스의 구현 예를 보여줍니다.
데이터 항목
다음 코드는 User 데이터 항목을 정의합니다. 각 User 인스턴스는 앱 데이터베이스의 user 테이블에 있는 행 하나를 나타냅니다.
다음 코드는 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)}
자바
@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);}
참고: 앱이 단일 프로세스에서 실행되면 AppDatabase 객체를 인스턴스화할 때 싱글톤 디자인 패턴을 따라야 합니다. 각 RoomDatabase 인스턴스는 리소스를 상당히 많이 소비하며 단일 프로세스 내에서 여러 인스턴스에 액세스해야 하는 경우는 거의 없습니다.
앱이 여러 프로세스에서 실행되는 경우 데이터베이스 빌더 호출에 enableMultiInstanceInvalidation()을 포함하세요. 이렇게 하면 각 프로세스에 AppDatabase 인스턴스가 있을 때 한 프로세스에서 공유 데이터베이스 파일을 무효화할 수 있으며 이 무효화는 다른 프로세스 내의 AppDatabase 인스턴스로 자동 전파됩니다.
사용
데이터 항목과 DAO, 데이터베이스 객체를 정의한 후에는 다음 코드를 사용하여 데이터베이스 인스턴스를 만들 수 있습니다.
이 페이지에 나와 있는 콘텐츠와 코드 샘플에는 콘텐츠 라이선스에서 설명하는 라이선스가 적용됩니다. 자바 및 OpenJDK는 Oracle 및 Oracle 계열사의 상표 또는 등록 상표입니다.
최종 업데이트: 2025-08-27(UTC)
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["필요한 정보가 없음","missingTheInformationINeed","thumb-down"],["너무 복잡함/단계 수가 너무 많음","tooComplicatedTooManySteps","thumb-down"],["오래됨","outOfDate","thumb-down"],["번역 문제","translationIssue","thumb-down"],["샘플/코드 문제","samplesCodeIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-08-27(UTC)"],[],[],null,["Save data in a local database using Room\nPart of [Android Jetpack](/jetpack).\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\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\nKotlin \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\nGroovy \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\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\nThis section presents an example implementation of a Room database with a single\ndata entity and a single DAO.\n\nData 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\nKotlin \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\nJava \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\nData 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\nKotlin \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\nJava \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\nDatabase\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\nKotlin \n\n```kotlin\n@Database(entities = [User::class], version = 1)\nabstract class AppDatabase : RoomDatabase() {\n abstract fun userDao(): UserDao\n}\n```\n\nJava \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\nUsage\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\nKotlin \n\n```kotlin\nval db = Room.databaseBuilder(\n applicationContext,\n AppDatabase::class.java, \"database-name\"\n ).build()\n```\n\nJava \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\nKotlin \n\n```kotlin\nval userDao = db.userDao()\nval users: List\u003cUser\u003e = userDao.getAll()\n```\n\nJava \n\n```java\nUserDao userDao = db.userDao();\nList\u003cUser\u003e users = userDao.getAll();\n```\n\nAdditional resources\n\nTo learn more about Room, see the following additional resources:\n\nSamples\n\nCodelabs\n\n- Android Room with a View [(Java)](/codelabs/android-room-with-a-view) [(Kotlin)](/codelabs/android-room-with-a-view-kotlin)\n\nBlogs\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)"]]