如何更新 hibernate 的每类表层次结构策略中的具体类?

发布于 2024-12-29 00:17:01 字数 803 浏览 1 评论 0 原文

我已经采用了 Hibernate 的每类表层次结构 此处

我有一个简单的一层层次结构,其中父级包含许多属性,子级包含更多相同的属性。与对象之间也存在关系。例如:

@Table(uniqueConstraints = { @UniqueConstraint(columnNames = {"name"}) })
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.STRING, length = 1)
abstract class X {
...
Long id;
String name;
List<A> a;
...
}
class Y extends X {
...
String getType() { return "Y"; }
...
}
class Z extends X {
...
String getType() { return "Z"; }
...
}
class A {}

我需要做的是将 Y 的持久实例“更新”为保持完整性的 Z 实例。如果我发出删除Y;创建 Z 时,我遇到了唯一约束违规(由于 hibernate 的删除顺序遵循创建/更新),但没有找到将 Y“更新”为 Z 的策略。

I've employed hibernate's table-per-class-hierarchy as outlined here.

I've got a simple 1-tier hierarchy where the parent includes a number of attributes and the child(ren) include more of the same. There are also relationships to the the object. For example:

@Table(uniqueConstraints = { @UniqueConstraint(columnNames = {"name"}) })
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.STRING, length = 1)
abstract class X {
...
Long id;
String name;
List<A> a;
...
}
class Y extends X {
...
String getType() { return "Y"; }
...
}
class Z extends X {
...
String getType() { return "Z"; }
...
}
class A {}

What I need to do is "update" a persisted instance of Y to an instance of Z maintaining integrity. If I issue delete Y; create Z, I get unique constraint violations (due to hibernate's ordering of deletes to follow creates/updates) but have found no strategy to "update" Y to Z.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

甜味拾荒者 2025-01-05 00:17:01

AFAIK,如果不完全绕过会话,就无法做到这一点,因为这意味着 Java 对象会更改其具体类型,而这是不可能的。即便如此,如果并发事务同时更新同一实体,您最好具有乐观并发性。如果另一个事务刷新实体或延迟加载实体,并且类型已更改,则会遇到问题。

简而言之,如果您需要这样做,则可能意味着您一开始就不应该拥有继承。考虑将表映射为具有类型列和可选字段的单个实体。

AFAIK, there's no way to do that without bypassing the session completely, since it would mean that a Java object changes its concrete type, which is impossible. And even then, if a concurrent transaction updates the same entity at the same time, you'd better have optimistic concurrency. And if another transaction refreshes the entity or lazy loads it, and the type has changed, you will have problems.

In short, if you need to do this, it probably means that you shouldn't have inheritance in the first place. Consider mapping the table as a single entity, with a type column, and optional fields.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文