英文:
Objectbox inherit properties from base class (which is NOT an entity itself)
问题
我有一个简单的基类,在其中我想要有一些共同的字段,比如 id 等。这个基类本身不是一个实体(Entity)。
public class Base {
@Id
protected long id;
protected String someOtherCommonProperty;
}
我还有一个实体类,它继承了基类。
@Entity
public class Entity extends Base {
String name;
String address;
}
我期望这个实体类能够继承基类的字段,但实际上我得到的是
[ObjectBox] 找不到 'Entity' 的 @Id 属性,请在一个非空的 long 属性上添加 @Id。
除了使用接口并且有很多重复的代码之外,是否有其他解决方法呢?
英文:
I have a simple base class in which I want to have some common fields, like id etc. The base class is not an Entity by itself.
public class Base {
@Id
protected long id;
protected String someOtherCommonProperty;
}
And I have an entity class, extending the base class.
@Entity
public class Entity extends Base {
String name;
String address;
}
I would expect the entity class to inherit the fields from the base class, but what I get is
[ObjectBox] No @Id property found for 'Entity', add @Id on a not-null long property.
Is there any way to fix that, besides using interfaces and have a lot of duplicated code?
答案1
得分: 3
你可以使用 @BaseEntity
注解。详细信息请查阅文档:Objectbox - Entity Inheritence。
无耻地抄袭以供将来参考:
> 除了 @Entity
注解之外,我们还引入了 @BaseEntity
注解,用于基类,可以替代 @Entity
使用。
有三种类型的基类,可以通过注解进行定义:
- 无注解:基类及其属性不会被用于持久化。
@BaseEntity
:属性会被用于子类的持久化,但基类本身无法被持久化。@Entity
:属性会被用于子类的持久化,并且基类本身是一个正常持久化的实体。
示例:
// 基类:
@BaseEntity
public abstract class Base {
@Id long id;
String baseString;
public Base() {
}
public Base(long id, String baseString) {
this.id = id;
this.baseString = baseString;
}
}
// 子类:
@Entity
public class Sub extends Base {
String subString;
public Sub() {
}
public Sub(long id, String baseString, String subString) {
super(id, baseString);
this.subString = subString;
}
}
英文:
You can use the @BaseEntity
annotation.
Have a look at the documentation: Objectbox - Entity Inheritence.
Shameless copy for future reference:
> In addition to the @Entity
annotation, we introduced a @BaseEntity
annotation for base classes, which can be used instead of @Entity
.
There three types of base classes, which are defined via annotations:
- No annotation: The base class and its properties are not considered for persistence.
@BaseEntity
: Properties are considered for persistence in sub classes, but the base class itself cannot be persisted.@Entity
: Properties are considered for persistence in sub classes, and the base class itself is a normally persisted entity.
Example:
// base class:
@BaseEntity
public abstract class Base {
@Id long id;
String baseString;
public Base() {
}
public Base(long id, String baseString) {
this.id = id;
this.baseString = baseString;
}
}
// sub class:
@Entity
public class Sub extends Base {
String subString;
public Sub() {
}
public Sub(long id, String baseString, String subString) {
super(id, baseString);
this.subString = subString;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论