Room 지속성 라이브러리를 사용하면 SQLite API를 직접 사용하는 것보다 여러 가지 이점이 있습니다.
SQL 쿼리의 컴파일 시간 확인
반복적이고 오류가 발생하기 쉬운 상용구 코드를 최소화하는 편의 주석
간소화된 데이터베이스 이전 경로
앱에서 현재 Room이 아닌 SQLite 구현을 사용한다면 이 페이지에서 Room을 사용하도록 앱을 이전하는 방법을 알아보세요. 앱에서 사용하는 첫 번째 SQLite 구현이 Room이라면 기본 사용법 정보는 Room을 사용하여 로컬 데이터베이스에 데이터 저장을 참고하세요.
이전 단계
다음 단계를 따라 SQLite 구현을 Room으로 이전하세요. SQLite 구현에서 대규모 데이터베이스나 복잡한 쿼리를 사용한다면 점진적으로 Room으로 이전하는 것이 좋습니다. 증분 이전 전략은 증분 이전을 참고하세요.
종속 항목 업데이트
앱에서 Room을 사용하려면 적절한 종속 항목을 앱의 build.gradle 파일에 포함해야 합니다. 최신 Room 종속 항목은 설정을 참고하세요.
모델 클래스를 데이터 항목으로 업데이트
Room은 데이터 항목을 사용하여 데이터베이스의 테이블을 나타냅니다. 각 항목 클래스는 테이블 하나를 나타내며 해당 테이블의 열을 의미하는 필드가 있습니다. 다음 단계를 따라 기존 모델 클래스를 Room 항목으로 업데이트하세요.
클래스 선언에 @Entity 주석을 달아 Room 항목임을 표시합니다. 선택적으로 tableName 속성을 사용하여 결과 테이블의 이름이 클래스 이름과 달라야 한다고 표시할 수 있습니다.
데이터베이스 버전 번호가 변경되므로 Room에서 데이터베이스에 기존 데이터를 유지하도록 Migration 객체를 정의하여 이전 경로를 표시해야 합니다.
데이터베이스 스키마가 변경되지 않는 한 이 구현은 빈 구현일 수 있습니다.
Kotlin
valMIGRATION_1_2=object:Migration(1,2){overridefunmigrate(database:SupportSQLiteDatabase){// Empty implementation, because the schema isn't changing.}}
Java
staticfinalMigrationMIGRATION_1_2=newMigration(1,2){@Overridepublicvoidmigrate(SupportSQLiteDatabasedatabase){// Empty implementation, because the schema isn't changing.}};
이 페이지에 나와 있는 콘텐츠와 코드 샘플에는 콘텐츠 라이선스에서 설명하는 라이선스가 적용됩니다. 자바 및 OpenJDK는 Oracle 및 Oracle 계열사의 상표 또는 등록 상표입니다.
최종 업데이트: 2025-07-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-07-27(UTC)"],[],[],null,["# Migrate from SQLite to Room\n\nThe Room persistence library provides a number of benefits over using the SQLite\nAPIs directly:\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\nIf your app currently uses a non-Room implementation of SQLite, read this page\nto learn how to migrate your app to use Room instead. If Room is the first\nSQLite implementation that you are using in your app, see [Save data in a local\ndatabase using Room](/training/data-storage/room) for basic usage information.\n\nMigration steps\n---------------\n\nPerform the following steps to migrate your SQLite implementation to Room. If\nyour SQLite implementation uses a large database or complex queries, you might\nprefer to migrate to Room gradually. See [Incremental migration](#incremental)\nfor an incremental migration strategy.\n\n### Update dependencies\n\nTo use Room in your app, you must include the appropriate dependencies in your\napp's `build.gradle` file. See [Setup](/training/data-storage/room#setup) for\nthe most up-to-date Room dependencies.\n\n### Update model classes to data entities\n\nRoom uses [data entities](/training/data-storage/room/defining-data) to\nrepresent the tables in the database. Each entity class represents a table and\nhas fields that represent columns in that table. Follow these steps to update\nyour existing model classes to be Room entities:\n\n1. Annotate the class declaration with [`@Entity`](/reference/kotlin/androidx/room/Entity) to indicate that it is a Room entity. You can optionally use the [`tableName`](/reference/kotlin/androidx/room/Entity#tablename) property to indicate that the resulting table should have a name that is different from the class name.\n2. Annotate the primary key field with [`@PrimaryKey`](/reference/kotlin/androidx/room/PrimaryKey).\n3. If any of the columns in the resulting table should have a name that is different from the name of the corresponding field, annotate the field with [`@ColumnInfo`](/reference/kotlin/androidx/room/ColumnInfo) and set the [`name`](/reference/kotlin/androidx/room/ColumnInfo#name) property to the correct column name.\n4. If the class has fields that you do not want to persist in the database, annotate those fields with [`@Ignore`](/reference/kotlin/androidx/room/Ignore) to indicate that Room should not create columns for them in the corresponding table.\n5. If the class has more than one constructor method, indicate which constructor Room should use by annotating all of the other constructors with `@Ignore`.\n\n### Kotlin\n\n```kotlin\n@Entity(tableName = \"users\")\ndata class User(\n @PrimaryKey\n @ColumnInfo(name = \"userid\") val mId: String,\n @ColumnInfo(name = \"username\") val mUserName: String?,\n @ColumnInfo(name = \"last_update\") val mDate: Date?,\n)\n```\n\n### Java\n\n```java\n@Entity(tableName = \"users\")\npublic class User {\n\n @PrimaryKey\n @ColumnInfo(name = \"userid\")\n private String mId;\n\n @ColumnInfo(name = \"username\")\n private String mUserName;\n\n @ColumnInfo(name = \"last_update\")\n private Date mDate;\n\n @Ignore\n public User(String userName) {\n mId = UUID.randomUUID().toString();\n mUserName = userName;\n mDate = new Date(System.currentTimeMillis());\n }\n\n public User(String id, String userName, Date date) {\n this.mId = id;\n this.mUserName = userName;\n this.mDate = date;\n }\n\n}\n```\n\n### Create DAOs\n\nRoom uses data access objects (DAOs) to define methods that access the database.\nFollow the guidance in [Accessing data using Room\nDAOs](/training/data-storage/room/accessing-data) to replace your existing query\nmethods with DAOs.\n\n### Create a database class\n\nImplementations of Room use a database class to manage an instance of the\ndatabase. Your database class should extend\n[`RoomDatabase`](/reference/kotlin/androidx/room/RoomDatabase) and reference all\nof the entities and DAOs that you have defined.\n**Note:** The migration to Room represents a SQLite database version change, so make sure that you increment the version number by one. \n\n### Kotlin\n\n```kotlin\n@Database(entities = [User::class], version = 2)\n@TypeConverters(DateConverter::class)\nabstract class UsersDatabase : RoomDatabase() {\n abstract fun userDao(): UserDao\n}\n```\n\n### Java\n\n```java\n@Database(entities = {User.class}, version = 2)\n@TypeConverters(DateConverter.class)\npublic abstract class UsersDatabase extends RoomDatabase {\n public abstract UserDao userDao();\n}\n```\n\n### Define a migration path\n\nSince the database version number is changing, you must define a\n[`Migration`](/reference/kotlin/androidx/room/migration/Migration) object to\nindicate a migration path so that Room keeps the existing data in the database.\nAs long as the database schema does not change, this can be an empty\nimplementation. \n\n### Kotlin\n\n```kotlin\nval MIGRATION_1_2 = object : Migration(1, 2) {\n override fun migrate(database: SupportSQLiteDatabase) {\n // Empty implementation, because the schema isn't changing.\n }\n}\n```\n\n### Java\n\n```java\nstatic final Migration MIGRATION_1_2 = new Migration(1, 2) {\n @Override\n public void migrate(SupportSQLiteDatabase database) {\n // Empty implementation, because the schema isn't changing.\n }\n};\n```\n\nTo learn more about database migration paths in Room, see [Migrate your\ndatabase](/training/data-storage/room/migrating-db-versions).\n\n### Update the database instantiation\n\nAfter you have defined a database class and a migration path, you can use\n[`Room.databaseBuilder`](/reference/kotlin/androidx/room/Room#databasebuilder)\nto create an instance of your database with the migration path applied: \n\n### Kotlin\n\n```kotlin\nval db = Room.databaseBuilder(\n applicationContext,\n AppDatabase::class.java, \"database-name\"\n )\n .addMigrations(MIGRATION_1_2).build()\n```\n\n### Java\n\n```java\ndb = Room.databaseBuilder(\n context.getApplicationContext(),\n UsersDatabase.class, \"database-name\"\n )\n .addMigrations(MIGRATION_1_2).build();\n```\n\n### Test your implementation\n\nMake sure you test your new Room implementation:\n\n- Follow the guidance in [Test\n migrations](/training/data-storage/room/migrating-db-versions#test) to test your database migration.\n- Follow the guidance in [Test your\n database](/training/data-storage/room/testing-db#test) to test your DAO methods.\n\nIncremental migration\n---------------------\n\nIf your app uses a large, complex database, it might not be feasible to migrate\nyour app to Room all at once. Instead, you can optionally implement the data\nentities and Room database as a first step and then migrate your query methods\ninto DAOs later. You can do this by replacing your custom [database helper\nclass](/training/data-storage/sqlite#DbHelper) with the\n[`SupportSQLiteOpenHelper`](/reference/kotlin/androidx/sqlite/db/SupportSQLiteOpenHelper)\nobject that you receive from\n[`RoomDatabase.getOpenHelper()`](/reference/kotlin/androidx/room/RoomDatabase#getopenhelper).\n\nAdditional resources\n--------------------\n\nTo learn more about migrating from SQLite to Room, see the following additional\nresources:\n\n### Blogs\n\n- [7 Steps to Room](https://medium.com/androiddevelopers/7-steps-to-room-27a5fe5f99b2)\n- [Incrementally migrate from SQLite to Room](https://medium.com/androiddevelopers/incrementally-migrate-from-sqlite-to-room-66c2f655b377)"]]