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

8-2) ํ”„๋ก์‹œ์™€ ์—ฐ๊ด€๊ด€๊ณ„ ๊ด€๋ฆฌ : ์ง€์—ฐ ๋กœ๋”ฉ๊ณผ ์ฆ‰์‹œ ๋กœ๋”ฉ

iseunghan 2020. 11. 21. 15:37
๋ฐ˜์‘ํ˜•

์ž๋ฐ” ORM ํ‘œ์ค€ JPA ํ”„๋กœ๊ทธ๋ž˜๋ฐ - ๊ธฐ๋ณธํŽธ์„ ๊ณต๋ถ€ํ•˜๋ฉฐ ์ •๋ฆฌํ•œ ๋‚ด์šฉ์ž…๋‹ˆ๋‹ค.

 

์ž๋ฐ” ORM ํ‘œ์ค€ JPA ํ”„๋กœ๊ทธ๋ž˜๋ฐ - ๊ธฐ๋ณธํŽธ - ์ธํ”„๋Ÿฐ

JPA๋ฅผ ์ฒ˜์Œ ์ ‘ํ•˜๊ฑฐ๋‚˜, ์‹ค๋ฌด์—์„œ JPA๋ฅผ ์‚ฌ์šฉํ•˜์ง€๋งŒ ๊ธฐ๋ณธ ์ด๋ก ์ด ๋ถ€์กฑํ•˜์‹  ๋ถ„๋“ค์ด JPA์˜ ๊ธฐ๋ณธ ์ด๋ก ์„ ํƒ„ํƒ„ํ•˜๊ฒŒ ํ•™์Šตํ•ด์„œ ์ดˆ๋ณด์ž๋„ ์‹ค๋ฌด์—์„œ ์ž์‹ ์žˆ๊ฒŒ JPA๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ดˆ๊ธ‰ ์›น ๊ฐœ๋ฐœ ํ”„๋กœ๊ทธ๏ฟฝ

www.inflearn.com

 

์ง€์—ฐ ๋กœ๋”ฉ(LAZY)์„ ์‚ฌ์šฉํ•ด์„œ ํ”„๋ก์‹œ๋กœ ์กฐํšŒ

@Entity
public class Member {
	
    @Id @GeneratedValue
    private Long id;
    
    @Column(name = "USERNAME")
    private String name;
    
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "TEAM_ID")
    private Team team;
    ..
    ..

}

@OneToMany, @ManyToMany ๋Š” ๊ธฐ๋ณธ์ด LAZY

 

LAZY (์ง€์—ฐ ๋กœ๋”ฉ)์„ ์‚ฌ์šฉํ•˜๋ฉด?

member๋ฅผ ์กฐํšŒํ•ด๋„ team์„ ์ง์ ‘ ์‚ฌ์šฉํ•˜๊ธฐ ์ „๊นŒ์ง„ ์กฐํšŒํ•˜์ง€ ์•Š๋Š”๋‹ค. (ํ”„๋ก์‹œ ๊ฐ์ฒด๋ฅผ ๋„ฃ์–ด์ค€๋‹ค)

Team team = member.getTeam(); // ์ด๋•Œ๋Š” ํ”„๋ก์‹œ ๊ฐ์ฒด!!

team.getName(); // team์„ ์‹ค์ œ๋กœ ์‚ฌ์šฉํ•˜๋Š” ์‹œ์ ์— DB์กฐํšŒ ์ฟผ๋ฆฌ๊ฐ€ ๋‚ ๋ผ๊ฐ€๊ฒŒ ๋œ๋‹ค.

 

๊ฐ€๊ธ‰์ ์ด๋ฉด ์ง€์—ฐ ๋กœ๋”ฉ๋งŒ ์‚ฌ์šฉ (์‹ค๋ฌด์—์„œ๋Š” ํŠนํžˆ ๋”!)

 

์ฆ‰์‹œ ๋กœ๋”ฉ(EAGER)์„ ์‚ฌ์šฉํ•ด์„œ ํ•จ๊ป˜ ์กฐํšŒ

@Entity
public class Member {
	
    @Id @GeneratedValue
    private Long id;
    
    @Column(name = "USERNAME")
    private String name;
    
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "TEAM_ID")
    private Team team;
    ..
    ..

}

@ManyToOne, @OneToOne๋Š” ๊ธฐ๋ณธ์ด EAGER

 

EAGER (์ฆ‰์‹œ ๋กœ๋”ฉ)์„ ์‚ฌ์šฉํ•˜๋ฉด?

member๋ฅผ ์กฐํšŒํ•˜๋ฉด team๊นŒ์ง€ ๋‹ค ์กฐํšŒํ•ด ๋ฒ„๋ฆฐ๋‹ค. team์—๋„ ์‹ค์ œ ์—”ํ‹ฐํ‹ฐ๊ฐ€ ๋“ค์–ด๊ฐ€๊ฒŒ ๋˜๊ณ , ์ฟผ๋ฆฌ๋ฅผ ๋ฏธ๋ฆฌ ํ•œ๋ฐฉ์— ๋‹ค ๋‚ ๋ ค๋ฒ„๋ฆฐ๋‹ค. (๋‚˜์ค‘์— ๋ฐฐ์šฐ๊ฒŒ ๋  ๊ฒƒ์ธ๋ฐ, JPQL์—์„œ N+1 ๋ฌธ์ œ๋ฅผ ์ผ์œผํ‚จ๋‹ค! )

 

JPQL N+1 ๋ฌธ์ œ๋ฅผ fetch join ์œผ๋กœ ๋ถ€๋ถ„์ ์œผ๋กœ ํ•ด๊ฒฐ์‹œํ‚ฌ ์ˆ˜ ์žˆ๋‹ค.

fetch join์„ ์‚ฌ์šฉํ•˜๋ฉด ํ•œ๋ฐฉ ์ฟผ๋ฆฌ๋ฅผ ๋‚ ๋ ค์„œ, ์ดํ›„์— ๋ฐ์ดํ„ฐ๋ฅผ ์กฐํšŒํ•ด๋„ ์ฟผ๋ฆฌ๊ฐ€ ๋‚˜๊ฐ€์ง€ ์•Š๋Š”๋‹ค.

            List<Member> list = em.createQuery("select m from Member m join fetch m.team", Member.class)
                    .getResultList();

 


 

์ง€์—ฐ ๋กœ๋”ฉ ํ™œ์šฉ

  • Member์™€ Team์€ ์ž์ฃผ ํ•จ๊ป˜ ์‚ฌ์šฉ ? ์ฆ‰์‹œ ๋กœ๋”ฉ
  • Member์™€ Order๋Š” ๊ฐ€๋” ์‚ฌ์šฉ -> ์ง€์—ฐ ๋กœ๋”ฉ
  • Order์™€ Product๋Š” ์ž์ฃผ ํ•จ๊ป˜ ์‚ฌ์šฉ -> ์ฆ‰์‹œ ๋กœ๋”ฉ

 

 

๋งˆ์ง€๋ง‰์œผ๋กœ..

  • ๋ชจ๋“  ์—ฐ๊ด€๊ด€๊ณ„์— ์ง€์—ฐ ๋กœ๋”ฉ์„ ์‚ฌ์šฉํ•ด๋ผ.
  • ์‹ค๋ฌด์—์„œ ์ฆ‰์‹œ ๋กœ๋”ฉ์„ ์‚ฌ์šฉํ•˜์ง€ ๋งˆ๋ผ. ( ์ƒ์ƒ๋„ ๋ชปํ•œ ์ฟผ๋ฆฌ๊ฐ€ ๋‚˜๊ฐ€์„œ ์–ด๋ ต๋‹ค.)
  • JPQL fetch ์กฐ์ธ์ด๋‚˜, ์—”ํ‹ฐํ‹ฐ ๊ทธ๋ž˜ํ”„ ๊ธฐ๋Šฅ์„ ์‚ฌ์šฉํ•ด๋ผ.

 

๋ฐ˜์‘ํ˜•