Monday, June 26, 2017

Improving the design of a JPA polymorphic association

Leave a Comment

I have the following JPA entity hierarchy:

class diagram for jpa entities

Upon logging in to the application a user has an instance of UserAccount in session; then depending on the concrete type of the organization associated to that UserAccount (Admin, Business or Family), a different dashboard/screen is displayed to the user e.g. if the user is a Business, then the dashboard for that business is displayed.

My concern with that design is that I have to do a instanceof check each time a user logs in so that I know which type of dashboard to display. I could also avoid that instanceof check by having a property in UserAccount such as organizationType (which would take one of three values) but then there would be redundant information.

Is there a way to improve my design? If so how?

1 Answers

Answers 1

Be greedy and get both, without redundancy.

Depending on the inheritance strategy, you may already have the organizationType info and you can expose it for free.

@Entity @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = "DTYPE") public abstract class AbstractOrganization implements Serializable {     @Id     protected Long id;      @Column(name = "DTYPE", insertable = false, updatable = false)     protected String organizationType;      ...  } 

the same applies also to the JOINED strategy.

Do not implement the setOrganizationType method.

Since a discriminator is required for simulating hierarchies with tables (except TABLE_PER_CLASS strategy), there's no redundancy and JPA provider will handle this attribute for you.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment