Objectify - should I create an entity super class?

166 views Asked by At

Is there any reason why shouldn't all my entities be subclasses of one generic ModelEntity object?

@Entity
public class ModelEntity {
    @Id Long id;
}

@Subclass
public class User extends ModelEntity {
    @Index
    String username;
}

The advantages are clear: there is code common to all entities (like id, date, getKey) Can you think of disadvantages?

2

There are 2 answers

0
stickfigure On BEST ANSWER

It can be helpful to have a common base class, but you almost certainly do not want to make it part of a polymorphic entity hierarchy. Don't use @Subclass for this purpose; you don't need it:

public class ModelEntity {
    @Id Long id;
}

@Entity
public class User extends ModelEntity {
    @Index
    String username;
}
0
gurghet On

Well, one of the great advantages of the jpa abstractions is to have insulation between the persistence layer and business logic. If you use an hidden id for all your entities you are giving up on that.

For example you could have a value object with your implementation so that you are actually hiding the @Id part of your entity. You could the use a completely different @Id for "real" entities.