gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 08:39:52 32 4
gpt4 key购买 nike

我的 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/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com