Android Room defaultValue ="CURRENT_TIMESTAMP"不起作用

标签 android sqlite android-room

我正在尝试为我的实体实现 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。

enter image description here

更改 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;

结果:-

enter image description here

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/

相关文章:

c# - Android 应用程序和 MySql 连接无法连接。打开

android - 透明Activity独立开启

java - sqlite中的超时异常

android - 如何通过自定义列表在房间中创建TypeConverter?

android - Regexp_substr() 函数等效于 Android 中的 RoomDatabase

java - 无法创建 com.example.architectureexample.NoteViewModel 类的实例

java - Android TTS 中没有声音 - 上下文错误?

android - 这是在 Android 中的光标处插入文本的正确方法吗?

java - 更新 SQLite 数据

php - 使用 php 以读取模式访问 sqlite 数据库的最佳方法