실전! 스프링 데이터 JPA을 듣고 정리한 내용입니다.
Member
와 Team
은 다대일 관계
FK
)는 Member
가 갖는다.
Member 엔티티
package study.datajpa.entity;
import lombok.*;
import javax.persistence.*;
@Entity
@Getter
@Setter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@ToString(of = {"id", "username", "age"})
public class Member {
@Id @GeneratedValue
@Column(name = "member_id")
private Long id;
private String username;
private int age;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "team_id")
private Team team;
public Member(String username) {
this.username = username;
}
public Member(String username, int age, Team team) {
this.username = username;
this.age = age;
if (team != null) {
changeTeam(team);
}
}
public void changeTeam(Team team) {
this.team = team;
team.getMembers().add(this);
}
}
@Setter
: 가급적 사용하지말자.@NoArgsConstructor AccessLevel.PROTECTED
: 기본 생성자를 막고 싶은데 JPA 스펙상 PROTECTED
로 열어두어야 한다.protected Member() {}
를 만들어 준다.@ToString
은 가급적 내부 필드(연관관계 없는 필드)만 넣자!team
을 넣으면 안된다!changeTeam()
으로 양방향 연관관계 한번에 처리(연관관계 편의 메서드)
Team 엔티티
package study.datajpa.entity;
import lombok.*;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
@Getter @Setter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@ToString(of = {"id", "name"})
public class Team {
@Id @GeneratedValue
@Column(name = "team_id")
private Long id;
private String name;
@OneToMany(mappedBy = "team")
private List<Member> members = new ArrayList<>();
public Team(String name) {
this.name = name;
}
}
Member
와 Team
은 양방향 연관관계Member.team
이 연관관계의 주인Team.members
는 연관관계의 주인이 아니다.따라서 Member.team
은 데이터베이스 외래키 값을 변경할 수 있지만, Team.members
는 읽기만 가능하다.
MemberTest - 데이터 확인 테스트
package study.datajpa.entity;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
@Transactional
@SpringBootTest
@Rollback(value = false)
class MemberTest {
@PersistenceContext
EntityManager em;
@Test
public void testEntity() {
Team teamA = new Team("teamA");
Team teamB = new Team("teamB");
em.persist(teamA);
em.persist(teamB);
Member member1 = new Member("member1", 10, teamA);
Member member2 = new Member("member2", 20, teamA);
Member member3 = new Member("member3", 30, teamA);
Member member4 = new Member("member4", 40, teamA);
em.persist(member1);
em.persist(member2);
em.persist(member3);
em.persist(member4);
// 초기화
em.flush();
em.clear();
// 확인
List<Member> members = em.createQuery("select m from Member m", Member.class).getResultList();
for (Member member : members) {
System.out.println("member = " + member);
System.out.println("member.getTeam() = " + member.getTeam());
}
}
}
실행 결과