Programming/JPA
Discriminate Mapping
Albothyl
2019. 5. 26. 16:55
1 Table - 2 Entity 의 경우에 사용한다. 즉 같은 구조를 가지고 있지만, 서로 다른 Entity로 사용해야할 경우 유용하다.
- 실제 테이블의 구조를 가지고 있는 Child Root Entity에 @DiscriminatorColumn을 추가하여 구분값이 있는 Column을 지정한다.
- Child Entity는 Child Root Entity에 설정한 Column의 값 중 @DiscriminatorValue에 설정한 값으로 Grouping 된다.
- 주의점 : 각 엔티티로 Mapping 할 때는 서로 다른 column으로 Join해야 한다. 같은 column으로 Join하려면 아래와 같은 옵션을 추가한다.
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
<property name="hibernate.discriminator.force_in_select" value="true"/>
</properties>
Parent Entity
- @OneToOne(mappedBy = "someEntity", cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
@Entity
@Table(schema = "any", name = "some_entity")
public class SomeEntity extends CreatedAndModifiedEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long someEntityId;
private String name;
@OneToOne(mappedBy = "someEntity", cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
private SomeMandatoryParameter someMandatoryParameter;
@OneToMany(mappedBy = "someEntity", cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
private List<SomeOptionalParameter> someOptionalParameters;
}
Child Entity 1
- @DiscriminatorValue("Mandatory")
@Entity
@DiscriminatorValue("Mandatory")
public class SomeMandatoryParameter extends SomeParameter {
@OneToOne
@JoinColumn(name = "someEntityId")
private SomeEntity someEntity;
}
Child Entity 2
- @DiscriminatorValue("Optional")
@Entity
@DiscriminatorValue("Optional")
public class SomeOptionalParameter extends SomeParameter {
@ManyToOne
@JoinColumn(name = "someEntityId")
private SomeEntity someEntity;
}
Child Entity's Root Entity
- @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
- @DiscriminatorColumn(name = "parameterGroup")
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "parameterGroup")
@Table(schema = "any", name = "some_parameter")
public abstract class SomeParameter extends CreatedAndModifiedEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long someParameterId;
private String name;
private String type;
private Boolean mandatory;
}