我正在尝试为我的实体实现 Room 2.2 附带的架构默认值,但它似乎不起作用。
我有一个名为 Place 的实体:
@Entity
public class Place implements Parcelable {
@PrimaryKey(autoGenerate = true)
private Long placeId;
private String name;
private double latitude;
private double longitude;
private int radius;
@ColumnInfo(defaultValue = "CURRENT_TIMESTAMP")
private String createdAt;
@Ignore
public Place() {}
public Place(String name, double latitude, double longitude, int radius) {
this.name = name;
this.latitude = latitude;
this.longitude = longitude;
this.radius = radius;
}
// getters and setters...
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
}
将地点插入数据库时,
createdAt
字段总是被插入为 NULL。更改
createdAt
变量为 long
用 0 替换字段。我在这里做错了什么?
最佳答案
您可以使用 @查询 具有特定的列名(和值),不包括那些默认为。
按照 :-
Note that the default value you specify here will NOT be used if you simply insert the Entity with @Insert. In that case, any value assigned in Java/Kotlin will be used. Use @Query with an INSERT statement and skip this column there in order to use this default value. defaultValue
因此,在这种情况下,您可以使用:-
@Query("INSERT INTO Place (name,latitude,longitude,radius) VALUES(:name,:latitude,:logitude,:radius)")
原因是除了rowid的别名。如果在显式或隐式指定列名的情况下传递 null,则不使用默认值,因此值存储为 null。
考虑 :-
DROP TABLE IF EXISTS place;
CREATE TABLE IF NOT EXISTS `Place` (`placeId` INTEGER PRIMARY KEY AUTOINCREMENT, `name` TEXT, `latitude` REAL NOT NULL, `longitude` REAL NOT NULL, `radius` INTEGER NOT NULL, `createdAt` TEXT DEFAULT CURRENT_TIMESTAMP);
INSERT INTO place VALUES(null,'opt1',0,0,0,null); //<<<< As per @Insert
INSERT INTO place (name,latitude,longitude,radius) VALUES('opt2',1,1,1); //<<<< As per @Query
SELECT * FROM place;
结果:-
Room 实际上构建了以下 2 个查询(根据生成的代码)
"INSERT OR ABORT INTO `Place` (`placeId`,`name`,`latitude`,`longitude`,`radius`,`createdAt`) VALUES (?,?,?,?,?,?)"
和
"INSERT INTO place (name,latitude,longitude,radius) VALUES(?, ?, ?, ?)"
关于Android Room defaultValue ="CURRENT_TIMESTAMP"不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59340430/