不是 Room 数据库迁移中的原始类型
not primitive types in Room database migration
我正在我的 Room 数据库中添加新实体 FeedItem 并为其编写迁移。
问题:我的 FeedItem class 中有一个 Date 类型,它不是原始类型。在这种情况下写迁移的正确方法是什么?
@Entity(tableName = "FeedItem")
public class FeedItem implements Item, Votable {
private int id;
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "feedItemRowIndex")
private int rowIndex;
private int toId;
private int fromId;
private Date date;
...
我的迁移目前看起来像这样。
private static final Migration MIGRATION_1_2 = new Migration(1, 2) {
@Override
public void migrate(@NonNull SupportSQLiteDatabase database) {
database.execSQL("CREATE TABLE FeedItem (feedItemId INTEGER, " +
"feedItemRowIndex INTEGER, " +
"feedVotes INTEGER" +
"feedVote INTEGER" +
"toId INTEGER" +
"fromId INTEGER" +
"date Date" + // i need to change this row
...
"PRIMARY KEY (feedItemRowIndex))"
这里是日期类型的转换器
public class DateConverter {
@TypeConverter
public static Date toDate(Long timestamp) {
return timestamp == null ? null : new Date(timestamp);
}
@TypeConverter
public static Long toTimestamp(Date date) {
return date == null ? null : date.getTime();
}
}
谢谢!
如果在您的 build.gradle 文件中设置了 room.schemaLocation,那么您可以查看生成的架构并复制 Room 用于创建 table.
Complete example here
这很容易。 Room 生成适合转换器类型的原始类型。
所以在我的例子中,类型是 INTEGER。感谢@EpicPandaForce 的评论
我正在我的 Room 数据库中添加新实体 FeedItem 并为其编写迁移。
问题:我的 FeedItem class 中有一个 Date 类型,它不是原始类型。在这种情况下写迁移的正确方法是什么?
@Entity(tableName = "FeedItem")
public class FeedItem implements Item, Votable {
private int id;
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "feedItemRowIndex")
private int rowIndex;
private int toId;
private int fromId;
private Date date;
...
我的迁移目前看起来像这样。
private static final Migration MIGRATION_1_2 = new Migration(1, 2) {
@Override
public void migrate(@NonNull SupportSQLiteDatabase database) {
database.execSQL("CREATE TABLE FeedItem (feedItemId INTEGER, " +
"feedItemRowIndex INTEGER, " +
"feedVotes INTEGER" +
"feedVote INTEGER" +
"toId INTEGER" +
"fromId INTEGER" +
"date Date" + // i need to change this row
...
"PRIMARY KEY (feedItemRowIndex))"
这里是日期类型的转换器
public class DateConverter {
@TypeConverter
public static Date toDate(Long timestamp) {
return timestamp == null ? null : new Date(timestamp);
}
@TypeConverter
public static Long toTimestamp(Date date) {
return date == null ? null : date.getTime();
}
}
谢谢!
如果在您的 build.gradle 文件中设置了 room.schemaLocation,那么您可以查看生成的架构并复制 Room 用于创建 table. Complete example here
这很容易。 Room 生成适合转换器类型的原始类型。
所以在我的例子中,类型是 INTEGER。感谢@EpicPandaForce 的评论