JPA/Hibernate:子类型与策略“模式”

发布于 2024-12-03 11:26:54 字数 739 浏览 1 评论 0原文

以下是 JPA 带注释的类型层次结构,其中所有数据字段(以及关联的 getter 和 setter)都是超类型的成员,以及用于实现业务逻辑的抽象方法。有任意数量的子类型实现这些抽象方法而不添加数据成员,因此我们使用单表继承策略,这样我们只需要数据库中的一张表来支持这种类型层次结构。

我这样做是因为,根据数据的内容,必须实施不同的行为才能实现最终目标。

@Entity
@Table
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn
public abstract class SuperEntity {
  // Several fields and getters and setters
  ...
  // Abstract method declarations for business logic
  ...
}

@Entity
@DiscriminatorValue("some value")
public class SomeSubtype extends SuperEntity {
  // Implementations of abstract methods
  ...
}

这是对 JPA/Hibernate 中鉴别器列概念的歪曲吗?

一位同事认为,由于数据的结构不会因子类型而异,因此抽象方法和相应的实现应该转移到类似策略模式方法的方式中。他的想法更好吗?

The following is a JPA annotated type hierarchy, in which all data fields (and associated getters and setters) are members of the supertype along with abstract methods for implementing business logic. There are any number of subtypes which implement these abstract methods without adding data members, thus we use single table inheritance strategy so that we need only one table in the database to back this type hierarchy.

I've done it this way because, based on the content of the data, there are different behaviors that must be implemented to achieve an ultimate goal.

@Entity
@Table
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn
public abstract class SuperEntity {
  // Several fields and getters and setters
  ...
  // Abstract method declarations for business logic
  ...
}

@Entity
@DiscriminatorValue("some value")
public class SomeSubtype extends SuperEntity {
  // Implementations of abstract methods
  ...
}

Is this a perversion of the discriminator column concept in JPA/Hibernate?

A co-worker argues that since the structure of the data does not vary from sub-type to sub-type, the abstract methods and corresponding implementations should be moved into something like a strategy pattern approach. Is his notion better?

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

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

发布评论

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

评论(1

情话难免假 2024-12-10 11:26:54

更好是非常主观的。听起来组合和策略是一个有效的替代方案,这可能会阻止您需要为业务逻辑的每个实现映射另一个实体。

除了 JPA 和 hibernate 之外,我读过的每一本 OO 设计书籍都以“优先考虑组合而不是继承”来共享行为。

假设您有一个数据对象,您是否不能在每个非休眠策略之间共享该对象并对其进行操作?无论如何,JPA/hibernate 越少,眼睛就越舒服。

Better is extremely subjective. It sounds like composition and strategies are a valid alternative, and that might prevent you from needing to map another entity for every implementation of the business logic.

JPA and hibernate aside, every OO design book I've ever read starts with "favor composition over inheritance" for sharing behavior.

Supposing you had one data object, couldn't you share the object between each non-hibernate strategy and operate on that? Having less JPA/hibernate is easier on the eyes, at any rate.

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