[Spring] JPA 중복 컬럼 상속으로 생성하는 방법

    스프링 Jpa 중복 컬럼 상속으로 생성하는 방법 알아보기

    예를 들어, User 엔티티와 Admin 엔티티가 있고, 이 두 엔티티는 모두 ID와 NAME 필드를 가진다고 가정해보겠습니다. 이때 중복된 ID와 NAME 컬럼을 상속 받는 BaseEntity를 생성하고, User와 Admin은 BaseEntity를 상속받도록 하면 중복 코드를 줄일 수 있습니다.

    @Entity
    @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
    public abstract class BaseEntity {
     
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        protected Long id;
     
        protected String name;
     
        // Getter and Setter
    }

    BaseEntity 클래스를 추상 클래스로 선언하고, @Inheritance 어노테이션의 strategy 속성값을 InheritanceType.TABLE_PER_CLASS로 지정하여, 상속 구조를 테이블 전략으로 구현할 수 있습니다.

    그리고 BaseEntity 클래스에서는 중복되는 ID와 NAME 필드를 정의하고, 각각의 하위 클래스에서 상속받도록 합니다.

    @Entity
    public class User extends BaseEntity {
     
        private String email;
     
        // Getter and Setter
    }
    @Entity
    public class Admin extends BaseEntity {
     
        private String password;
     
        // Getter and Setter
    }

    User와 Admin 엔티티에서는 각각의 특정 필드를 추가로 정의하고, BaseEntity를 상속받도록 지정합니다.

    이렇게 BaseEntity 클래스를 생성하여 중복 코드를 제거하면, 코드의 유지보수성과 가독성이 높아지고, 엔티티 클래스의 중복된 코드를 최소화할 수 있습니다.

    댓글

    Designed by JB FACTORY