티스토리 뷰

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;
}

'Programming > JPA' 카테고리의 다른 글

Basic Mapping  (0) 2019.05.30
Embedded Mapping  (0) 2019.05.29
Query DSL, Criteria 설정  (0) 2019.03.01
Query DSL  (0) 2018.08.05
Hibernate Criteria  (0) 2018.08.05
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함