gpt4 book ai didi

java - Hibernate中的继承策略 : making an entity abstract and replacing with sub classes

转载 作者:行者123 更新时间:2023-11-29 06:20:33 24 4
gpt4 key购买 nike

我目前有现有的数据库和 hibernate 映射。有一个中央表和相应的实体 (PersistentObject)。许多其他表和实体通过 @ManyToOne@OneToOne 映射引用 PersistentObject

现在我想对当前的PersistentObject进行抽象,引入继承自PeristentObject<的两个子类Sub1ObjectSub2Object/.

我无法更改存储 PersistentObject 的表,否则可以添加新表等。该表包含足够的信息,因此我可以在需要时使用例如 @DiscriminatorColumn 来分隔 Sub1ObjectSub2Object 行。

是否可以进行此更改,以便我当前的 HQL 查询无需修改即可继续工作?我有很多查询,例如 from PersistentObject where foo = ?from OtherEntity other where other.persistentObject = ?。我希望这些查询开始返回具体的子类而不是父类(super class)。我不想为 Sub1ObjectSub2Object 编写单独的查询。

这有可能吗?我应该使用什么继承策略?

最佳答案

I can't change the table where PersistentObject is stored, otherwise adding new tables etc is possible. The table contains enough information so that I can use e.g @DiscriminatorColumn to separate Sub1Object and Sub2Object rows if needed.

您可以使用JOINED 继承策略(有或没有鉴别器)。对于头等舱:

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name = "DISC")
public abstract PersistentObject {

@Id @GeneratedValue
private Long id;

...
}

例如:

@Entity
public class Sub1Object extends PersistentObject {
...
}

这不会更改现有表。

Is it possible to make this change so that my current HQL queries still work without modifications? I have lot of queries like from PersistentObject where foo = ? and from OtherEntity other where other.persistentObject = ?. I'd like that those queries start returning concrete subclasses instead of the super class.

它们将工作并返回扩展该类的所有持久类的实例。

关于java - Hibernate中的继承策略 : making an entity abstract and replacing with sub classes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3210607/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com