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

5 - 2) ์—ฐ๊ด€๊ด€๊ณ„ ๋งคํ•‘ ๊ธฐ์ดˆ - ๋‹จ๋ฐฉํ–ฅ ์—ฐ๊ด€๊ด€๊ณ„

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

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

 

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

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

www.inflearn.com

 

โœ…๊ฐ์ฒด ์ง€ํ–ฅ ๋ชจ๋ธ๋ง ( ๊ฐ์ฒด ์—ฐ๊ด€๊ด€๊ณ„ ์‚ฌ์šฉ )

@Entity
public class Member {
	@Id @GenerateValue
    private Long id;
    
    @ManyToOne	// Member์‹œ์ ์œผ๋กœ ๋‹ค๋Œ€์ผ์ด๋ฏ€๋กœ, ManyToOne!
    @JoinColumn(name = "TEAM_ID")
    private Team team;
    
    @Column(name = "USERNAME")
    private String name;
}

@ManyToOne @JoinColumn(name  = "TEAM_ID") ์œผ๋กœ ์—ฐ๊ด€๊ด€๊ณ„๋ฅผ ๋งคํ•‘์‹œ์ผœ์ค€๋‹ค.

@Entity
public class Team {
	@Id @GenerateValue
    private Long id;
    
    private String name;
}

 

โœ…๊ฐ์ฒด ์ง€ํ–ฅ ๋ชจ๋ธ๋ง ( ORM ๋งคํ•‘ )

์—ฐ๊ด€๊ด€๊ณ„ ์ €์žฅ

Team team = new Team();
...
em.persist(team);

Member member = new Member();
...
member.setTeam(team); // ๋‹จ๋ฐฉํ–ฅ ์—ฐ๊ด€๊ด€๊ณ„ ์„ค์ •, ์ฐธ์กฐ ์ €์žฅ
em.persist(member);

 

์ฐธ์กฐ๋กœ ์—ฐ๊ด€๊ด€๊ณ„ ์กฐํšŒ

//์กฐํšŒ
Member findMember = em.find(Member.class , member.getId());
//์ฐธ์กฐ๋ฅผ ์‚ฌ์šฉํ•ด์„œ ์—ฐ๊ด€๊ด€๊ณ„ ์กฐํšŒ
Team FindTeam = findMember.getTeam();

 

์—ฐ๊ด€๊ด€๊ณ„ ์ˆ˜์ •

// ์ƒˆ๋กœ์šด Team
Team teamB = new Team();
teamB.setName("TeamB");
em.persist(teamB);

// member์— ์ƒˆ๋กœ์šด Team์œผ๋กœ ์ˆ˜์ •
member.setTeam(teamB);

 

๋‹ค์Œ์œผ๋กœ๋Š”, "์–‘๋ฐฉํ–ฅ ์—ฐ๊ด€๊ด€๊ณ„์˜ ์ฃผ์ธ"์— ๋Œ€ํ•ด์„œ ๊ณต๋ถ€ํ•ด๋ณด์ž.

๋ฐ˜์‘ํ˜•