Inheritance in entities, using objectbox

892 views Asked by At

In my code I put some base fields in base abstract 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;
    }
}

So, in child class User I am not define an id field:

@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
}

because it defined in superclass. I don't want to create in every class an id field, and don't want to persist in database BaseEntity class. And I get an error: Error:[ObjectBox] Code generation failed: No ID property found for Entity User (package:...)

How can I use objectbox with an inheritance?

2

There are 2 answers

0
Markus Junginger On BEST ANSWER

Polymorphism of entities is not supported at this time, but there is a feature request.

If it helps, you can go for an interface. E.g.:

public interface BaseEntity {
    long getId();
}

Note: you could have a setter for the ID, but my personal advice would be to have the id field package private (so ObjectBox has access from generated classes) and not have a setter because it would suggest it's OK to change the ID at any time.

Update: ObjectBox 1.4 introduced entity inheritance (non-polymorphic).

2
Velmurugan V On

@Oleg Objectbox don't support inheritance in entity class as it will map every entity to a separate table in db and use this @Id variable as unique id to identify a row(entity instance) in that table. Thus @Id variable is must for every entity class.

In general,

for each for Child class to access Parent class variables it have to be either protected or public but in your id is private so change it to either protected it will work.

    protected long id;

if you mark it is as protected only the parent and its child class can access it and when you mark it as public any class can access it. marking it as private means only parent class can access it