Java/Jakarta EE

JPA의 MappedSuperclass와 Embeddable의 차이 및 사용법

slowcloud_ 2025. 5. 27. 17:25

tl;dr

  • MappedSuperclass는 부모 클래스에, Embeddable은 내부에 포함하는 클래스에 사용하면 된다.
  • 둘 다 하나의 테이블로 합쳐진다.

MappedSuperclass

상속할 부모 클래스에 주로 사용한다.

아래 접은글에 자바 코드, 그리고 일대일 대응하는 SQL 코드를 작성해두었다.

더보기
@MappedSuperclass
public static class Account {

	@Id
	private Long id;

	private String owner;

	private BigDecimal balance;

	private BigDecimal interestRate;

	//Getters and setters are omitted for brevity

}

@Entity(name = "DebitAccount")
public static class DebitAccount extends Account {

	private BigDecimal overdraftFee;

	//Getters and setters are omitted for brevity

}

@Entity(name = "CreditAccount")
public static class CreditAccount extends Account {

	private BigDecimal creditLimit;

	//Getters and setters are omitted for brevity

}

 

CREATE TABLE DebitAccount (
    id BIGINT NOT NULL , -- Account에서 상속받은 내용들
    balance NUMERIC(19, 2) ,
    interestRate NUMERIC(19, 2) ,
    owner VARCHAR(255) ,
    overdraftFee NUMERIC(19, 2) , -- DebitAccount 속성
    PRIMARY KEY ( id )
)

CREATE TABLE CreditAccount (
    id BIGINT NOT NULL , -- Account에서 상속받은 내용들
    balance NUMERIC(19, 2) ,
    interestRate NUMERIC(19, 2) ,
    owner VARCHAR(255) ,
    creditLimit NUMERIC(19, 2) , -- CreditAccount 속성
    PRIMARY KEY ( id )
)

Embeddable

상속 대신 필드로 포함하는 경우에 사용한다. Embedded 어노테이션은 생략해도 된다.

역시 아래 접은글에 자바 코드, 그리고 일대일 대응하는 SQL 코드를 작성해두었다.

더보기
@Entity(name = "Book")
public static class Book {

	@Id
	@GeneratedValue
	private Long id;

	private String title;

	private String author;

	private Publisher publisher;

	//Getters and setters are omitted for brevity
}

@Embeddable
public static class Publisher {

	@Column(name = "publisher_name") // 구분을 위해 publisher_를 붙인 필드
	private String name;

	@Column(name = "publisher_country")
	private String country;

	//Getters and setters, equals and hashCode methods omitted for brevity

}

 

create table Book (
    id bigint not null,
    author varchar(255),
    publisher_country varchar(255), -- publisher의 속성
    publisher_name varchar(255), -- publisher의 속성
    title varchar(255),
    primary key (id)
)

참고