JPA @Entity继承

tra*_*ega 6 java inheritance persistence hibernate jpa

我一直在研究JPA/Hibernate @Entity继承一段时间,似乎无法找到解决我想要实现的问题的任何东西.

基本上我希望能够根据需要定义@Entity所有列和表映射.然后,我希望能够使用@Entity@Transient每个"子实体"的主体中定义的不同方法集来扩展许多不同的位置.这是我想要实现的基本示例,但到目前为止没有成功:

@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; }

}    
Run Code Online (Sandbox Code Playgroud)

.

@Entity
public class MountainEntity extends MountainEntityBase implements Serializable {

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

    @Transient
    public List<MountianEntity> getAllMountainsExploredBy(String explorerName){
        // Implementation 
    }
}
Run Code Online (Sandbox Code Playgroud)

所以任何扩展类都只@Transient在其体内定义s.但是我也希望允许子类为空的情况:

@Entity
public class MountainEntity extends MountainEntityBase implements Serializable {
}
Run Code Online (Sandbox Code Playgroud)

在此先感谢您的帮助.

Boz*_*zho 8

JPA中的继承是使用@Inheritance注释在根实体上指定的.在那里,您可以指定层次结构的数据库表示.查看文档以获取更多详细信息.

如果您的子类仅定义瞬态字段(而不是方法)(即未保存在数据库中),则可能是鉴别器列可能是最佳选择.但实际情况可能是您实际上不需要继承 - 主实体可以拥有所有方法(因为它具有方法操作的所有字段)

  • 对的,这是可能的.您只需指定一个鉴别器值.我链接了文档 - 这是必读的;) (2认同)