首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JPA @Entity继承

JPA @Entity继承
EN

Stack Overflow用户
提问于 2011-05-30 05:35:48
回答 1查看 13.4K关注 0票数 6

我研究JPA/Hibernate @Entity继承已经有一段时间了,似乎找不到任何可以解决我想要实现的问题的东西。

基本上,我希望能够根据需要定义一个包含所有列和表映射的@Entity。然后,我希望能够通过在每个“子实体”的主体中定义不同的@Transient方法集,在许多不同的位置扩展@Entity。这是我试图实现的一个基本示例,但到目前为止还没有成功:

代码语言:javascript
复制
@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; }

}    

代码语言:javascript
复制
@Entity
public class MountainEntity extends MountainEntityBase implements Serializable {

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

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

因此,任何扩展类都将在其主体中仅定义@Transient。但我也希望考虑到子类为空的情况:

代码语言:javascript
复制
@Entity
public class MountainEntity extends MountainEntityBase implements Serializable {
}

事先感谢你对此的任何帮助。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-05-30 05:41:52

JPA中的继承是使用@Inheritance注释在根实体上指定的。在这里,您可以指定层次结构的数据库表示。有关更多详细信息,请查看the documentation

如果您的子类只定义了瞬态字段(而不是方法)(即不保存在数据库中),那么鉴别器列可能是最佳选择。但也有可能你实际上并不需要继承-- main实体可以拥有所有的方法(因为它拥有方法操作的所有字段)。

票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6170564

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档