Spring

[Spring] ํ•ด์‹œํƒœ๊ทธ ๊ธฐ๋Šฅ DB + JPA ์„ค๊ณ„

DAHLIA CHOI 2023. 6. 20. 17:37

 

์บก์Šคํ†ค ์„ค๊ณ„๋ฅผ ํ•˜๋ฉด์„œ ํ•ด์‹œํƒœ๊ทธ ๊ธฐ๋Šฅ์„ ๊ตฌํ˜„ํ–ˆ์–ด์•ผ ํ–ˆ๋Š”๋ฐ ์–ด๋–ป๊ฒŒ ์„ค๊ณ„๋ฅผ ํ•ด์•ผ ํ• ์ง€ ๊ณ ๋ฏผ์ด ๋์—ˆ๋‹ค..๐Ÿค”

 

๋‚ด๊ฐ€ ๊ณ ๋ฏผํ–ˆ๋˜ ๊ฒƒ

๐Ÿ”ธ ๊ธ€์€ ์—ฌ๋Ÿฌ ๊ฐœ์˜ ํ•ด์‹œํƒœ๊ทธ๋ฅผ ๊ฐ€์งˆ ์ˆ˜ ์žˆ๋‹ค.

๐Ÿ”ธ ํ•ด์‹œํƒœ๊ทธ๋Š” ์—ฌ๋Ÿฌ ๊ธ€์— ์‚ฌ์šฉ ๋  ์ˆ˜ ์žˆ๋‹ค.

๐Ÿ‘‰ ๊ทธ๋Ÿผ DB ์ˆ˜์—… ๋“ค์—ˆ์„ ๋•Œ์ฒ˜๋Ÿผ N:M ๊ด€๊ณ„๋ฅผ ์จ์•ผ ํ•˜๋‚˜...?๋ผ๊ณ  ๊ณ ๋ฏผํ–ˆ์ง€๋งŒ N:M๊ด€๊ณ„๋Š” ์ ˆ๋Œ€์ ˆ๋Œ€์ ˆ๋Œ€ ์‚ฌ์šฉํ•˜๋ฉด ์•ˆ ๋œ๋‹ค๊ณ  ํ•ด์„œ ๋ฐฉ๋ฒ•์„ ์ฐพ์•„๋ดค๋‹ค!

โœ๏ธ ๋‹ค๋Œ€๋‹ค๋ฅผ ์‚ฌ์šฉํ•  ๊ฒฝ์šฐ์—๋Š” ๋„๋ฉ”์ธ ๋ชจ๋ธ์ด ๋‹จ์ˆœํ•ด์ง€๊ณ  ํŽธ๋ฆฌํ•œ ์žฅ์ ์ด ์žˆ๋‹ค. ํ•˜์ง€๋งŒ ์—”ํ‹ฐํ‹ฐ์— ์—ฌ๋Ÿฌ ๊ฐ’์ด ๋“ค์–ด๊ฐ€๊ฒŒ ๋˜๋Š”๋ฐ ์ถ”๊ฐ€ํ•œ ์นผ๋Ÿผ๋“ค์€ ๋งคํ•‘ํ•  ์ˆ˜ ์—†๋‹ค๊ณ  ํ•œ๋‹ค..! ๊ฒฐ๊ตญ @ManyToMany๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ๋ชปํ•จ..

 

 

ํ•ด๊ฒฐํ•œ ๋ฐฉ๋ฒ•

๐Ÿ”ธ ์ผ๋Œ€๋‹ค, ๋‹ค๋Œ€์ผ ๊ด€๊ณ„๋ฅผ ๋งŒ๋“ค์ž!

๐Ÿ”ธ ๋งคํ•‘ ์—”ํ‹ฐํ‹ฐ๋ฅผ ๋งŒ๋“ค์–ด ๊ธ€๊ณผ ๋งคํ•‘์—”ํ‹ฐํ‹ฐ๋Š” ์ผ๋Œ€๋‹ค, ๋งคํ•‘์—”ํ‹ฐํ‹ฐ์™€ ํ•ด์‹œํƒœ๊ทธ๋Š” ๋‹ค๋Œ€์ผ ๊ด€๊ณ„๋กœ ์„ค๊ณ„ํ•œ๋‹ค.

 

DB ์„ค๊ณ„

 

JPA ์„ค๊ณ„

 

Board

@Entity
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class Board extends BaseTimeEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "board_id")
    private Long id;
    
    @Column(name = "title", nullable = false)
    private String title;
    
    @Column(name = "content", nullable = false)
    private String content;

    @OneToMany(mappedBy = "board", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<TagMapping> tagMappings;
}
orphanRemoval์€ ๊ณ ์•„ ๊ฐ์ฒด๋ฅผ ์‚ญ์ œ์‹œ์ผœ์ฃผ๋Š” ์—ญํ• ์„ ํ•œ๋‹ค!

 

TagMapping

@Entity
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class TagMapping extends BaseTimeEntity {
    @Id
    @GeneratedValue
    @Column(name = "TagMapping_id")
    private Long id;

    @ManyToOne
    @JoinColumn(name = "board_id")
    private Board board;

    @ManyToOne
    @JoinColumn(name = "tag_id")
    private Tag tag;
}

 

Tag

@Entity
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class Tag extends BaseTimeEntity {

    @Id
    @GeneratedValue
    @Column(name = "tag_id")
    private Long id;
    
    @Column(name = "word", nullable = false)
    private String word;

    @OneToMany(mappedBy = "tag", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
    private List<TagMapping> tagMapping;
}

 

 

 

๋Š๋‚€์ 

๐Ÿ”ธ ์ด๋ ‡๊ฒŒ ํ•˜๋‹ˆ๊นŒ ๊ด€๋ฆฌ๊ฐ€ ํŽธํ•œ ๊ฒƒ ๊ฐ™์€ ๋Š๋‚Œ์ด ๋“ค์—ˆ๋‹ค!  ํŠน์ • ํ•ด์‹œํƒœ๊ทธ๋กœ ๊ฒ€์ƒ‰ํ•  ๋•Œ๋Š” ์กฐ์ธ์„ ์‚ฌ์šฉํ•ด์„œ ๊ธ€์„ ์ฐพ๋Š” ๊ธฐ๋Šฅ๋„ ์ž˜ ๋˜๋Š” ๊ฑธ ํ™•์ธํ–ˆ๋‹ค. ์ž˜ ํ•œ๊ฑด์ง„ ๋ชจ๋ฅด๊ฒ ์ง€๋งŒ ๋‚˜์ค‘์— ๋˜ ํ•ด๋ณผ ์ผ์ด ์žˆ๋‹ค๋ฉด ์ข€ ๋” ๋””๋ฒจ๋กญํ•ด๋ณด๊ณ  ์‹ถ๋‹ค.