๐ŸŒป JAVA/์ž๋ฐ” ORM ํ‘œ์ค€ JPA ํ”„๋กœ๊ทธ๋ž˜๋ฐ

6-2) ๋‹ค์–‘ํ•œ ์—ฐ๊ด€๊ด€๊ณ„ ๋งคํ•‘ : ๋‹ค๋Œ€๋‹ค[N:M]

iseunghan 2020. 10. 28. 09:59
๋ฐ˜์‘ํ˜•

๋‹ค๋Œ€๋‹ค ๋งคํ•‘์€ ์™ ๋งŒํ•˜๋ฉด ์•ˆ์“ฐ๋Š”๊ฒŒ ์ตœ์„ ์ด๋‹ค.

๋‹ค๋Œ€๋‹ค ๋งคํ•‘ ๋ฐฉ๋ฒ•์ด ๋‘๊ฐ€์ง€๊ฐ€ ์žˆ๋Š”๋ฐ

  1. @ManyToMany๋ฅผ ์‚ฌ์šฉํ•˜๋Š”๊ฒƒ์ด๋‹ค.
  2. ์—ฐ๊ฒฐ ํ…Œ์ด๋ธ”์šฉ ์—”ํ‹ฐํ‹ฐ ์ถ”๊ฐ€ํ•ด์„œ @OneToMany๋ฅผ ์‚ฌ์šฉ (์—ฐ๊ฒฐํ…Œ์ด๋ธ”์„ ์—”ํ‹ฐํ‹ฐ๋กœ ์Šน๊ฒฉ)

 

โœ…๋‹ค๋Œ€๋‹ค [N:M]

 

1. @ManyToMany ๋ฅผ ์‚ฌ์šฉ

MEMBER_PRODUCT ๋ผ๋Š” ์ค‘๊ฐ„ ํ…Œ์ด๋ธ”์ด ์ƒ์„ฑ์ด ๋œ๋‹ค.

@Entity
public class Member {
    @ManyToMany
    @JoinTable(name = "MEMBER_PRODUCT") // ์ด๋ ‡๊ฒŒ ํ•˜๋ฉด MEMBER_PRODUCT๋ผ๋Š” ํ…Œ์ด๋ธ”์ด ์ƒ์„ฑ๋œ๋‹ค.
    private List<Product> products = new ArrayList<>();

	// ๋‹ค๋ฅธ ๋ฉ”์†Œ๋“œ ์ƒ๋žต
}

@Entity
public class Product {
    @ManyToMany(mappedBy = "products")
    private List<Member> members = new ArrayList<>();

	// ๋‹ค๋ฅธ ๋ฉ”์†Œ๋“œ ์ƒ๋žต
}

 

2. @OneToMany , ์—ฐ๊ฒฐ ํ…Œ์ด๋ธ”์šฉ ์—”ํ‹ฐํ‹ฐ ์ถ”๊ฐ€

 

@Entity
public class Member_Product {
	@Id @GeneratedValue
    private Long id;
    
    ...
    
    @ManyToOne
    @JoinColumn(name = "MEMBER_ID")
    private Member member;
    
    @ManyToOne
    @JoinColumn(name = "PRODUCT_ID")
    priavet Product product;
    
    // ๋‹ค๋ฅธ ๋ฉ”์†Œ๋“œ ์ƒ๋žต
}
@Entity
public class Member {
	@OneToMany(mappedBy = "members")
    private  List<Member_Product> products = new ArrayList<>();
    
    // ๋‹ค๋ฅธ ๋ฉ”์†Œ๋“œ ์ƒ๋žต
}
@Entity
public class Product {
	@OneToMany(mappedBy = "product")
    private List<Member_Product> member_products = new ArrayList<>();
    
    // ๋‹ค๋ฅธ ๋ฉ”์†Œ๋“œ ์ƒ๋žต
}

 

๋ฐ˜์‘ํ˜•