JPA/Hibernate:子类型与策略“模式”
以下是 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
更好是非常主观的。听起来组合和策略是一个有效的替代方案,这可能会阻止您需要为业务逻辑的每个实现映射另一个实体。
除了 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.