【发布时间】:2019-03-29 15:23:55
【问题描述】:
我的类中有以下层次结构
@Entity
@Table(name = "Parent")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class Parent {
}
@Entity
@DiscriminatorVlaue("FirstChild")
public class FirstChild extends Parent {
}
@Entity
@DiscriminatorVlaue("SecondChild")
public class SecondChild extends Parent {
}
这会按预期创建一个表 Parent。
我的应用中的一些业务逻辑:
当请求被接受时,它被持久化为“父”类型并在表中创建以下条目
Dtype id value
Parent 1 "some value"
在处理请求时,它可以是 FirstChild 类型或 SecondChild 类型,所以在我的代码中我有
if (some condition is met) {
// change the Parent to its firstChild type
}
else {
// chnage it to "SecondChild" type
}
我对继承的理解和使用正确吗?我本质上是在抛出运行时异常的 if 循环中向下转换对象,但是更改对象的类型是否也会更改数据库中的 DTYPE 值?我本质上是使用继承来将事物组织为它们的类型。我可以在构造函数中做一些魔术来实现这一点吗?但真正的问题是 Dtype 在更新时可以修改吗?
为了进一步解决这个问题,
我在子类中创建了构造函数
public FirstChild(Parent parent) {
id = parent.id
}
但这会为子类型创建一个新行,
Dtype id value
Parent 1 "some value"
FirstChild 2 "some value"
我正在确保使用父 ID (1) 创建“firstChild”记录,但我不确定为什么要创建第二行
【问题讨论】:
-
对不起,这是一个复制粘贴错误,我确实有 DiscriminatorColumn,我只是想更改更新的类型
-
你不能,就像你不能改变Java中对象的类型一样。您可能应该使用 has-a 关联而不是 is-a。
-
那么用hibernate继承有什么价值呢?它在 Java 对象中非常有意义
-
写
// change the Parent to its firstChild type是什么意思?你的代码是什么样子的?
标签: java hibernate inheritance constructor