Room增加数据表迁移小结
-
Room使用注解方式增加数据表,进行迁移示例
-
1 使用@Entity注解增加实体类,示例:
@Entity(tableName = "notice") data class NoticeBean( @PrimaryKey(autoGenerate = true)var id: Int = 0, @ColumnInfo(name = "orderId")var orderId: Int = 0, @ColumnInfo(name = "title")var title: String? ="" )
-
2 在数据库持有者AppDatabase中增加创建的实体类,并更改version = 3(我原来version = 2),示例:
@Database(entities = arrayOf(GrabOrderBean::class,NoticeBean::class),version = 3) abstract class AppDatabase : RoomDatabase() {}
-
3 增加Migration并addMigrations,示例:
val MIGRATION_2_3 =object : Migration(2,3) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("CREATE TABLE IF NOT EXISTS notice (orderId INTEGER NOT NULL, title TEXT, " + "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)") } } private fun buildDatabase(context: Context) = Room.databaseBuilder(context.applicationContext, AppDatabase::class.java,"test.db") .allowMainThreadQueries() .addMigrations(MIGRATION_1_2,MIGRATION_2_3) .build()
-
4 注意事项
在定义实体类时orderId 有默认值,所以在执行execSQL时需使用orderId INTEGER NOT NULL,否则在运行时有可能会报异常。
-
网友评论