简体   繁体   English

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

[英]JPA/Hibernate: Sub-typing vs. strategy 'pattern'

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. 以下是JPA批注的类型层次结构,其中所有数据字段(以及关联的getter和setter)都是超类型的成员,以及用于实现业务逻辑的抽象方法。 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? 这是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? 他的观念更好吗?

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. 除了JPA和休眠之外,我读过的每本OO设计书籍都以“赞成继承而不是继承”作为共享行为的开头。

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. 无论如何,减少JPA /休眠状态在眼睛上都比较容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM