관리 메뉴

IT.FARMER

JPA Entity 상속 관계 만들기 ,@MappedSuperclass 본문

Spring/Spring Data JPA

JPA Entity 상속 관계 만들기 ,@MappedSuperclass

아이티.파머 2021. 5. 25. 11:06
반응형

@MappedSuperclass 이용한 상속

JPA Entity 에서 상속관계를 만들기 위해서는 @MappedSuperclass 를 사용하여 상속 관계를 정의 할 수 있다.
최상위 Class로 Employee 를 생성하고, 해당 Class를 상속 받아 관계를 정의할 수 있다.

예제 )

      @MappedSuperclass
      public class Employee {

          @Id protected Integer empId;
          @Version protected Integer version;
          @ManyToOne @JoinColumn(name="ADDR")
          protected Address address;

          public Integer getEmpId() { ... }
          public void setEmpId(Integer id) { ... }
          public Address getAddress() { ... }
          public void setAddress(Address addr) { ... }
      }

      // Default table is FTEMPLOYEE table
      @Entity
      public class FTEmployee extends Employee {

          // Inherited empId field mapped to FTEMPLOYEE.EMPID
          // Inherited version field mapped to FTEMPLOYEE.VERSION
          // Inherited address field mapped to FTEMPLOYEE.ADDR fk

          // Defaults to FTEMPLOYEE.SALARY
          protected Integer salary;

          public FTEmployee() {}

          public Integer getSalary() { ... }

          public void setSalary(Integer salary) { ... }
      }

      @Entity @Table(name="PT_EMP")
      @AssociationOverride(
          name="address", 
          joincolumns=@JoinColumn(name="ADDR_ID"))
      public class PartTimeEmployee extends Employee {

          // Inherited empId field mapped to PT_EMP.EMPID
          // Inherited version field mapped to PT_EMP.VERSION
          // address field mapping overridden to PT_EMP.ADDR_ID fk
          @Column(name="WAGE")
          protected Float hourlyWage;

          public PartTimeEmployee() {}

          public Float getHourlyWage() { ... }
          public void setHourlyWage(Float wage) { ... }
      }

subclass 에서는 @AttributeOverride 어노테이션을 이용하여, 속성 관계를 재정의 할 수 있다.
해당 예제에서는 기존 address 와 엮인 연관관계에서 @JoinColumn(name="ADDR") 을 컬럼으로 사용하였으나, 새로 정의한 @AssociationOverride 에서는 Join Column을, joincolumns=@JoinColumn(name="ADDR_ID")) 으로 재정의 하였다.

반응형