travega travega - 1 year ago 71
Java Question

JPA @Entity Inheritance

I have been looking into JPA/Hibernate

inheritance for a while now and can't seem to find anything that addresses what I am trying to achieve.

Basically I want to be able to define an
with all of the column and table mappings as required. Then I want to be able to extend the
in a number of different locations with different sets of
methods defined in the body of each "sub-Entity". This is a basic example of what I am trying to achieve but with no success thus far:

@Table(name = "mountain")
public class MountainEntityBase implements Serializable {
public Integer mountainId = 0;
public Integer height = 0;

public List<ExplorerEntityBase> explorers = new ArrayList<ExplorerEntityBase>();

@Column(name = "mountain_id")
public Integer getMountainId() { return mountainId; }
public void setMountainId(Integer mountainId) { this.mountainId = mountainId; }

public String getHeight() { return height; }
public void setHeight(String height) { this.height = height; }

public List<ExplorerEntityBase> getExplorers() { return this.explorers; }
public void setExplorers(List<ExplorerEntityBase> explorers) { this.explorers = explorers; }



public class MountainEntity extends MountainEntityBase implements Serializable {

public List<MountainEntity> allMountainsExploredBy = new ArrayList<MountainEntity>();

public List<MountianEntity> getAllMountainsExploredBy(String explorerName){
// Implementation

So any extended class will define only
s in its body. But also I want to allow for situations where the child class is empty:

public class MountainEntity extends MountainEntityBase implements Serializable {

Thanks in advance for any help with this.

Answer Source

Inheritance in JPA is specified on the root entity using the @Inheritance annotation. There you can specify the database representation of the hierarchy. Check the documentation for more details.

If your child classes define only transient fields (not methods) (i.e. not saved in the db), then perhaps a discriminator column is the best option. But it may be the case that you don't actually need inheritance - the main entity can have all the methods (because it has all the fields the methods operate on)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download