Pergunta

The following is a JPA annotated type hierarchy, in which all data fields (and associated getters and setters) are members of the supertype along with abstract methods for implementing business logic. There are any number of subtypes which implement these abstract methods without adding data members, thus we use single table inheritance strategy so that we need only one table in the database to back this type hierarchy.

I've done it this way because, based on the content of the data, there are different behaviors that must be implemented to achieve an ultimate goal.

@Entity
@Table
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn
public abstract class SuperEntity {
  // Several fields and getters and setters
  ...
  // Abstract method declarations for business logic
  ...
}

@Entity
@DiscriminatorValue("some value")
public class SomeSubtype extends SuperEntity {
  // Implementations of abstract methods
  ...
}

Is this a perversion of the discriminator column concept in JPA/Hibernate?

A co-worker argues that since the structure of the data does not vary from sub-type to sub-type, the abstract methods and corresponding implementations should be moved into something like a strategy pattern approach. Is his notion better?

Foi útil?

Solução

Better is extremely subjective. It sounds like composition and strategies are a valid alternative, and that might prevent you from needing to map another entity for every implementation of the business logic.

JPA and hibernate aside, every OO design book I've ever read starts with "favor composition over inheritance" for sharing behavior.

Supposing you had one data object, couldn't you share the object between each non-hibernate strategy and operate on that? Having less JPA/hibernate is easier on the eyes, at any rate.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top