实体中的继承,使用objectbox
Inheritance in entities, using objectbox
在我的代码中,我将一些基本字段放在基本摘要中 class BaseEntity
:
public abstract class BaseEntity {
@Id
private long id;
public BaseEntity() {
}
public BaseEntity(long id) {
this.id = id;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
因此,在子 class User
中,我没有定义 id
字段:
@Entity
public class User extends BaseEntity {
private String name;
private String login;
private String gender;
private String email;
private String phoneNumber;
private Date registrationDate;
private Date lastActivityDate;
private long systemId;
public User() {
}
...Getters and Setters
}
因为它定义在superclass中。我不想在每个 class 中创建一个 id
字段,也不想在数据库 BaseEntity
class 中持久化。我得到一个错误:
Error:[ObjectBox] Code generation failed: No ID property found for Entity User (package:...)
如何通过继承使用对象框?
@Oleg Objectbox 不支持实体 class 中的继承,因为它将每个实体映射到数据库中单独的 table 并使用此 @Id 变量作为唯一 ID 来标识行(实体实例)在 table 中。因此 @Id 变量对于每个实体都是必须的 class.
一般来说,
对于每个 Child class 访问 Parent class 变量,它必须被保护或 public 但是在你的 id 中是私有的所以将其更改为受保护即可。
protected long id;
如果您将其标记为受保护,则只有 parent 及其 child class 可以访问它,当您将其标记为 public 时,任何 class 可以访问它。
将其标记为私有意味着只有 parent class 可以访问它
目前不支持实体的多态性,但是有一个feature request。
如果有帮助,你可以去找一个接口。例如:
public interface BaseEntity {
long getId();
}
注意:您可以为 ID 使用 setter,但我个人的建议是将 id 字段包私有(这样 ObjectBox 可以从生成的 类 访问)并且没有setter 因为它会提示可以随时更改 ID。
更新: 引入了 ObjectBox 1.4 entity inheritance(非多态)。
在我的代码中,我将一些基本字段放在基本摘要中 class BaseEntity
:
public abstract class BaseEntity {
@Id
private long id;
public BaseEntity() {
}
public BaseEntity(long id) {
this.id = id;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
因此,在子 class User
中,我没有定义 id
字段:
@Entity
public class User extends BaseEntity {
private String name;
private String login;
private String gender;
private String email;
private String phoneNumber;
private Date registrationDate;
private Date lastActivityDate;
private long systemId;
public User() {
}
...Getters and Setters
}
因为它定义在superclass中。我不想在每个 class 中创建一个 id
字段,也不想在数据库 BaseEntity
class 中持久化。我得到一个错误:
Error:[ObjectBox] Code generation failed: No ID property found for Entity User (package:...)
如何通过继承使用对象框?
@Oleg Objectbox 不支持实体 class 中的继承,因为它将每个实体映射到数据库中单独的 table 并使用此 @Id 变量作为唯一 ID 来标识行(实体实例)在 table 中。因此 @Id 变量对于每个实体都是必须的 class.
一般来说,
对于每个 Child class 访问 Parent class 变量,它必须被保护或 public 但是在你的 id 中是私有的所以将其更改为受保护即可。
protected long id;
如果您将其标记为受保护,则只有 parent 及其 child class 可以访问它,当您将其标记为 public 时,任何 class 可以访问它。 将其标记为私有意味着只有 parent class 可以访问它
目前不支持实体的多态性,但是有一个feature request。
如果有帮助,你可以去找一个接口。例如:
public interface BaseEntity {
long getId();
}
注意:您可以为 ID 使用 setter,但我个人的建议是将 id 字段包私有(这样 ObjectBox 可以从生成的 类 访问)并且没有setter 因为它会提示可以随时更改 ID。
更新: 引入了 ObjectBox 1.4 entity inheritance(非多态)。