对象框从基础 class 继承属性(它本身不是实体)

Objectbox inherit properties from base class (which is NOT an entity itself)

我有一个简单的基础 class,我想在其中包含一些公共字段,例如 id 等。基础 class 本身不是一个实体。

public class Base {

    @Id
    protected long id;

    protected String someOtherCommonProperty;
}

我有一个实体 class,扩展了基础 class。

@Entity
public class Entity extends Base {

    String name;
    String address;
}

我希望实体 class 继承基础 class 的字段,但我得到的是

[ObjectBox] No @Id property found for 'Entity', add @Id on a not-null long property.

除了使用接口和大量重复代码之外,还有什么办法可以解决这个问题吗?

您可以使用 @BaseEntity 注释。
查看文档:Objectbox - Entity Inheritence.

无耻复制以供日后参考:


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:

  • 无注释:不考虑基础 class 及其属性的持久性。
  • @BaseEntity: 子classes中考虑持久化属性,但是基础class本身不能持久化。
  • @Entity: 属性在子 classes 中被认为是持久化的,基础 class 本身是一个正常持久化的实体。

示例:

    // 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;
        }
    }