JPA Best Practice #1 – Do not inherit id property

Especially when working with JPA v1.0, try not to use id inheritance. If the id property is inherited, the JPA Engine will try to keep its value unique along all instances of the abstracted class.
I will try to present this problem with a basic example representing a hierarchy of company items, tracked by their id within the company in order to keep a consistent inventory:

@Entity
public abstract class CompanyItem {
@Id private Long id;
// ... Constructor
// ... Other properties
// ... Getters and setters
}
@Entity
public class Stapler extends CompanyItem {
// ... Constructor
// ... Other properties
// ... Getters and setters
}
@Entity
public class Chair extends CompanyItem {
// ... Constructor
// ... Other properties
// ... Getters and setters
}

Example 1. Company item hierarchy.

This structure is not so bad at first sight since it solves the problem of unique id in a simple way. The problem here lies in the fact that whenever you create an instance of Stapler or Chair, the JPA engine will ensure the id for each object is unique among all instances of CompanyItem. This is not so bad if the system is small, but for a large system, it means that soon there will be a lack of ids for new objects.
A simple solution to this problem could be the definition of the id property on each not abstract class that is part of the hierarchy. This may pose a problem of non-uniqueness for each company item.
The following structure shows a simple solution to this problem:

@Entity
public abstract class CompanyItem {
// ... Constructor
// ... Other properties
// ... Getters and setters
}
@Entity
public class Stapler extends CompanyItem {
@Id private Long id;
// ... Constructor
// ... Other properties
// ... Getters and setters
}
@Entity
public class Chair extends CompanyItem {
@Id private Long id;
// ... Constructor
// ... Other properties
// ... Getters and setters
}

Example 2. Company item hierarchy “reloaded”.

Now you’ve seen it. The solution is simple and it is to lower down the id property to each instantiable class inheriting from CompanyItem
In the following post, I’m going to show other sorts of problems regarding relationships with abstract classes. I hope you enjoy it.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s