将数据库实体从 Java 转换为 Kotlin

Convert Database Entity from Java to Kotlin

我目前正在将我的项目转换为 Kotlin,并且我有一个使用 Java 的带有 Room 数据库的应用程序。

我在 Java

中的实体
@Entity(tableName = "store")
@Fts4
public class Store {

    @PrimaryKey
    @ColumnInfo(name = "rowid")
    private Long identification;

    @NonNull
    @ColumnInfo(name = "name")
    private String name;

    @ColumnInfo(name = "location")
    private String location;

    @ColumnInfo(name = "days_open")
    private int daysOpen;

    public Store(Long identification, @NonNull String name, String location, int daysOpen) {
        this.identification = identification;
        this.name = name;
        this.location = location;
        this.daysOpen = daysOpen
    }

    public Long getIdentification() {
        return identification;
    }

    @NonNull
    public String getName() {
        return name;
    }

    public String getLocation() {
        return location;
    }

    public int getDaysOpen() {
        return daysOpen;
    }
}

我这样转换成 Kotlin

@Entity(tableName = "store")
@Fts4
data class Store(

    @PrimaryKey @ColumnInfo(name = "rowid") 
    val identification: Long?,

    @ColumnInfo(name = "name")
    val name: String,

    @ColumnInfo(name = "location")
    val location: String?

    @ColumnInfo(name = "days_open")
    val daysOpen: Int?
)

现在我遇到了这个错误

java.lang.IllegalStateException: Room cannot verify the data integrity. Looks like you've changed schema but forgot to update the version number. You can simply fix this by increasing the version number.
 

我们真的需要在这做迁移吗?或者我错误地转换了东西。我正在使用 Room 2.3.0.

implementation "androidx.room:room-ktx:2.3.0"
kapt "androidx.room:room-compiler:2.3.0"

当我更新数据库版本时,出现了这个错误

java.lang.IllegalStateException: A migration from 1 to 2 was required but not found. Please provide the necessary Migration path via RoomDatabase.Builder.addMigration(Migration ...) or allow for destructive migrations via one of the RoomDatabase.Builder.fallbackToDestructiveMigration* methods.
   

我将此代码添加到我的数据库

val MIGRATION_1_2 = object : Migration(1, 2) {
    override fun migrate(database: SupportSQLiteDatabase) {
        database.execSQL("
        // put changes here
        ")}
}

我不知道在 migrate 函数中放什么。有什么想法吗?

异常消息似乎很清楚。您需要更新房间数据库的版本。 转到扩展 RoomDatabase 的 class 并增加 @Database 注释中 version 属性的值。

@Database(entities = [A::class, B::class], version = 2)
abstract class YourRoomDatabase: RoomDatabase() 

已经得到解决方案。

问题是我在 Java 中的 int 实体与 Kotlin 中的 Int 不同。因此,我需要通过迁移更新我的架构。我的解决方案被引用 here.