# [JPA] ๊ณ ๊ธ‰ ๋งคํ•‘ : ๋งคํ•‘ ์ •๋ณด๋งŒ ์ œ๊ณตํ•˜๊ธฐ using @MappedSuperClass
Study Repository

[JPA] ๊ณ ๊ธ‰ ๋งคํ•‘ : ๋งคํ•‘ ์ •๋ณด๋งŒ ์ œ๊ณตํ•˜๊ธฐ using @MappedSuperClass

by rlaehddnd0422

์•ž์„œ ๋ฐฐ์šด ์ƒ์† ๊ด€๊ณ„๋งคํ•‘์€ ๋ถ€๋ชจ ํด๋ž˜์Šค์™€ ์ž์‹ ํด๋ž˜์Šค ๋ชจ๋‘ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ํ…Œ์ด๋ธ”๊ณผ ๋งคํ•‘ํ–ˆ์Šต๋‹ˆ๋‹ค. 

๋งŒ์•ฝ ๋ถ€๋ชจ ํด๋ž˜์Šค๋Š” ํ…Œ์ด๋ธ”๊ณผ ๋งคํ•‘ํ•˜์ง€ ์•Š๊ณ  ๋ถ€๋ชจ ํด๋ž˜์Šค๋ฅผ ์ƒ์†๋ฐ›๋Š” ์ž์‹ ํด๋ž˜์Šค๋“ค์—๊ฒŒ ์ž์‹ ํด๋ž˜์Šค์—์„œ ๊ณตํ†ต์œผ๋กœ ์‚ฌ์šฉํ•˜๋Š” ๋งคํ•‘ ์ •๋ณด๋งŒ  ์ œ๊ณตํ•˜๊ณ  ์‹ถ์„ ๋•Œ ์–ด๋–ป๊ฒŒ ํ•  ์ˆ˜ ์žˆ์„๊นŒ์š”?

 

@MappedSuperClass๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค. ๋ฐ”๋กœ ์˜ˆ์‹œ๋ถ€ํ„ฐ ์‚ดํŽด๋ด…์‹œ๋‹ค.

 

@MappedSuperClass๋Š” ์ž๋ฐ”์˜ ์ถ”์ƒ ํด๋ž˜์Šค์™€ ๋งค์šฐ ๋น„์Šทํ•ฉ๋‹ˆ๋‹ค. @Entity๋Š” ์‹ค์ œ ๋งคํ•‘์ด ์ด๋ฃจ์–ด์ง€์ง€๋งŒ @MappedSuperClass๋Š” ์‹ค์ œ ํ…Œ์ด๋ธ”๊ณผ๋Š” ๋งคํ•‘๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๋‹จ์ˆœํžˆ ๋งคํ•‘์ •๋ณด๋ฅผ ์ƒ์†ํ•  ๋ชฉ์ ์œผ๋กœ๋งŒ ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค.

 

๋‹จ์ˆœํžˆ ์ž์‹ ํด๋ž˜์Šค์—์„œ ๊ณตํ†ต์œผ๋กœ ์‚ฌ์šฉํ•˜๋Š” ํ•„๋“œ๋ฅผ BaseEntity์— ๋ชจ์•„์„œ ๋งคํ•‘ ์ •๋ณด๋งŒ ์ œ๊ณตํ•˜๋„๋ก ์ƒ์† ๊ด€๊ณ„๋ฅผ ๋งคํ•‘ํ•ด๋ด…์‹œ๋‹ค.

@MappedSuperClass // @Entity X
public abstract class BaseEntity {

    @Id @GeneratedValue
    private Long id;
    private String nmae;
}

@Entity
public class Member extends BaseEntity {

    // ID ์ƒ์†
    // NAME ์ƒ์†
    private String email;
    
}

@Entity
public class Seller extends BaseEntity {

    // ID ์ƒ์†
    // NAME ์ƒ์†
    private String shopName;
    
}
  • ๋งคํ•‘ ์ •๋ณด๋งŒ ์ œ๊ณตํ•˜๊ธฐ ์œ„ํ•ด ๋ถ€๋ชจํด๋ž˜์Šค์— @Entity๊ฐ€ ์•„๋‹Œ @MappedSuperClass๋กœ ๋งคํ•‘ํ•ด์ค๋‹ˆ๋‹ค.

Entity ๊ธฐ๋ฐ˜ create ๊ฒฐ๊ณผ

 

๋ถ€๋ชจ๋กœ ๋ถ€ํ„ฐ ๋ฌผ๋ ค๋ฐ›์€ ๋งคํ•‘์ •๋ณด๋ฅผ ์žฌ์ •์˜ํ•˜๊ณ  ์‹ถ์œผ๋ฉด @AttributeOverrides๋‚˜ @AttributeOverride๋ฅผ ์‚ฌ์šฉํ•˜๊ณ , ์—ฐ๊ด€๊ด€๊ณ„๋ฅผ ์žฌ์ •์˜ํ•˜๋ ค๋ฉด @AssociationOverrides๋‚˜ @AssociationOverride๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.

 

@Entity
@AttributeOverrides({@AttributeOverride(name="id", column= @Column(name = "MEMBER_ID")),
				@AttributeOverride(name="name", column= @Column(name = "MEMBER_NAME"))})
public class Member extends BaseEntity {

 

<์ •๋ฆฌ>

  • @MappedSuperclass๋Š” ํ…Œ์ด๋ธ”๊ณผ๋Š” ๊ด€๊ณ„๊ฐ€ ์—†๊ณ  ๋‹จ์ˆœํžˆ ์—”ํ‹ฐํ‹ฐ๊ฐ€ ๊ณตํ†ต์œผ๋กœ ์‚ฌ์šฉํ•˜๋Š” ๋งคํ•‘์ •๋ณด๋ฅผ ๋ชจ์•„์ฃผ๋Š” ์—ญํ• ์„ ํ•ฉ๋‹ˆ๋‹ค. 

<์ฐธ๊ณ ์ž๋ฃŒ>

๋ธ”๋กœ๊ทธ์˜ ์ •๋ณด

Study Repository

rlaehddnd0422

ํ™œ๋™ํ•˜๊ธฐ