java - 必须用@NonNull(复合主键)注释主键

标签 java android

我的 Android 项目中有以下 Java 类。

@Entity
public class Daily {

    @PrimaryKey
    private Date dailyId;

    //Other non important attrs, getters, setters, etc.

}

@Entity(primaryKeys = {"dailyId", "dailyDetailId"})
public class DailyDetail {

    private Date dailyId; //which is the value of its unique parent.
    private Long dailyDetailId;

    //Other non important attrs, getters, setters, etc.

}

顺便说一句:我已经添加了类型转换器。

当我尝试构建项目时出现以下错误:

You must annotate primary keys with @NonNull. "dailyId" is nullable. SQLite considers this a bug and Room does not allow it.

然后,当我按照说明将 @NonNull 添加到 dailyid 时,它显示 必须初始化非空字段 (?)

我应该如何解决这个问题?我的想法是初始化两个主键,但是当我尝试将新对象插入数据库时​​,这应该是一个问题。

最佳答案

Then, when I follow the instructions and add @NonNull to dailyid, it says Not-null fields must be initialized (?)

如果你用@NonNull注释一个字段,你就是在告诉编译器“这个东西永远不会为空”。但是Java中未初始化对象的默认值是多少呢?这是正确的! 。因此,如果您使用 @NonNull 注释字段,您必须初始化它以保证它不会从 null 开始。

How should I fix this?

初始化您的字段。 立即声明或在类构造函数中。

@NonNull
@PrimaryKey
private Date dailyId = new Date(); // Now it's initialized and not null

或者

@Entity
public class Daily {

    @NonNull
    @PrimaryKey
    private Date dailyId;

    public Daily() {
        dailyId = new Date(); // Now it's initialized and not null
    }

    // ^- this AND / OR this -v

    // Note here that if using an argument in the constructor, it too must be
    // annotated as @NonNull to tell the compiler that you're setting the value
    // of your non-nullable field to something that won't itself be null
    public Daily(@NonNull Date initialDate) {
        dailyId = initialDate; // Now it's initialized and not null
    }
}

希望有帮助!

关于java - 必须用@NonNull(复合主键)注释主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61444648/

相关文章:

Java多线程-将参数传递给单个实例

JavaFX:在 ButtonBar 内对齐按钮(使用 SceneBuilder 或 fxml)

java - 验证错误: Value is required error for list selection event

java - 为什么当我单击按钮时我的页面不存在?

Android 布局最大宽度或屏幕宽度?

java - 使用 Java 从 TrueType 字体渲染重音字符在某些系统上看起来是错误的

java - 如何模拟 Tinkerpop 蓝图顶点和边缘对象?

android - 如何为 Android 6.0.1 构建 OpenSSL 1.0.2?

android - cordova(phonegap)作为应用程序和在 phonegap 应用程序内部工作不同

android - 什么类型的谷歌地图 api 用于搜索特定地点,如医院