有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法将表添加到文件室数据库,日志中的异常表示“预期”表与“已找到”表不同

我正在尝试将第二个表添加到我的房间数据库中,但在运行应用程序时出现以下异常

java.lang.IllegalStateException: Migration didn't properly handle people_table(com.example.soundguard.People).
     Expected:
    TableInfo{name='people_table', columns={name=Column{name='name', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=1}, priority=Column{name='priority', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0}}, foreignKeys=[], indices=[]}
     Found:
    TableInfo{name='people_table', columns={}, foreignKeys=[], indices=[]}

我创建了一个类:

@Entity(tableName = "people_table")
public class People {

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

    @NonNull
    @ColumnInfo(name = "priority")
    private int mPriority;

    public People(@NonNull String name, @NonNull int priority) {
        this.mName = name;
        this.mPriority = priority;
    }

    public String getName(){return this.mName;}
    public int getPriority(){return this.mPriority;}
    public void setPriority(int priority){this.mPriority = priority;}
}

并在数据库类中添加了第二个实体和迁移,因此我不确定找到的表与预期的表不匹配的原因:

@Database(entities = {AppName.class, People.class}, version = 4, exportSchema = true)
public abstract class SoundguardRoomDatabase extends RoomDatabase {

...

static final Migration MIGRATION_3_4 = new Migration(3, 4) {
        @Override
        public void migrate(SupportSQLiteDatabase database) {
            database.execSQL("CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`name` TEXT NOT NULL, `priority` INTEGER NOT NULL, PRIMARY KEY(`name`))");
        }
    };

共 (1) 个答案

  1. # 1 楼答案

    我不相信您可以在java中使用${your_variable},这是Kotlin代码。因此,您创建的表将使用以下方法创建:-

    CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`name` TEXT NOT NULL, `priority` INTEGER NOT NULL, PRIMARY KEY(`name`))
    

    也就是说,表名应该是${table_name}而不是people_table,因此它什么也找不到

    因此,请尝试使用:-

    @Database(entities = {AppName.class, People.class}, version = 4, exportSchema = true)
    public abstract class SoundguardRoomDatabase extends RoomDatabase {
    
        ...
    
        static final Migration MIGRATION_3_4 = new Migration(3, 4) {
                @Override
                public void migrate(SupportSQLiteDatabase database) {
                    database.execSQL("CREATE TABLE IF NOT EXISTS `" + TABLE_NAME + "` (`name` TEXT NOT NULL, `priority` INTEGER NOT NULL, PRIMARY KEY(`name`))");
                }
            };