向实体添加新字段
Posted
技术标签:
【中文标题】向实体添加新字段【英文标题】:Adding a new field to an entity 【发布时间】:2020-07-01 14:07:30 【问题描述】:我创建了一个director
类
@Entity(tableName = "director")
public class Director
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "did")
public int id;
@ColumnInfo(name = "full_name")
@NonNull
public String fullName;
public Director(@NonNull String fullName)
this.fullName = fullName;
我决定通过添加迁移方法和向类添加字段来添加新列
@Entity(tableName = "director")
public class Director
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "did")
public int id;
@ColumnInfo(name = "full_name")
@NonNull
public String fullName;
@ColumnInfo(name = "age")
public int age;
public Director(@NonNull String fullName)
this.fullName = fullName;
方法
static final Migration MIGRATION_1_2 = new Migration(1, 2)
@Override
public void migrate(SupportSQLiteDatabase database)
String query = "ALTER TABLE 'director' ADD COLUMN 'age' INTEGER ";
database.execSQL(query);
;
当我执行代码时出现此错误
Caused by: java.lang.IllegalStateException: Migration didn't properly handle
它说它是预期的
age=Columnname='year', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0, defaultValue='null',
找到了
age=Columnname='year', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0, defaultValue='null',
我可以看到问题出在“notnull”部分,但如何解决这个问题?我希望它为空。
【问题讨论】:
对于非空值,您必须提供默认值。 【参考方案1】:尝试将默认年龄值设置为 0
static final Migration MIGRATION_1_2 = new Migration(1, 2)
@Override
public void migrate(SupportSQLiteDatabase database)
database.execSQL(
"ALTER TABLE 'director' ADD COLUMN 'age' INTEGER NOT NULL DEFAULT 0"
);
;
【讨论】:
以上是关于向实体添加新字段的主要内容,如果未能解决你的问题,请参考以下文章