Java – JPA @ entity inheritance

I have been studying JPA / Hibernate @ entity inheritance for some time, and it seems that I can't find anything to solve the problem I want to implement

Basically, I want to be able to define a @ entity that contains all column and table mappings as needed Then, I want to be able to extend @ entity in multiple different locations using different sets of @ transient methods defined in the body of each "sub entity" This is the basic example I want to implement, but so far it has not been successful:

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

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

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

    @Column(name="height")
    public String getHeight() { return height; }
    public void setHeight(String height) { this.height = height; }

    @OneToMany(mappedBy="mountainId")
    public List<ExplorerEntityBase> getExplorers() { return this.explorers; }
    public void setExplorers(List<ExplorerEntityBase> explorers) { this.explorers = explorers; }

}

.

@Entity
public class MountainEntity extends MountainEntityBase implements Serializable {

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

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

Therefore, any extension class only defines @ transients. In its body However, I also want to allow the subclass to be empty:

@Entity
public class MountainEntity extends MountainEntityBase implements Serializable {
}

Thank you for your help

Solution

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 subclass defines only transient fields (not methods) (that is, they are not saved in the database), the discriminator column may be the best choice But the reality may be that you don't actually need to inherit - the main entity can own all the methods (because it has all the fields of the method operation)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>