다대일 (N:1) 관계에서는 

FK가 N에 들어가야 함.

 

Member

@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)  // ManyToOne은 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); // 객체기 때문에 반대쪽에도 바꿔줘야함
    }
}

Team

@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") // db 연관관계 세팅: mappedBy는 FK가 없는쪽에 걸어주는게 좋다
    private List<Member> members = new ArrayList<>();

    public Team(String name) {
        this.name = name;
    } 
}

 

 

 

Test

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;

@SpringBootTest
@Transactional  // 테스트 코드에서 사용시 테스트 종료 후 롤백 시킴
@Rollback(value = false)  // 롤백 안시키도록 설정
class MemberTest {

    @PersistenceContext
    EntityManager em; //JPA의 영속성 컨텍스트

    @Test
    public void testEntity(){
        Team teamA = new Team("teamA");
        Team teamB = new Team("teamB");
        em.persist(teamA);
        em.persist(teamB);

        Member merber1 = new Member("member1", 10, teamA);
        Member merber2 = new Member("member2", 20, teamA);
        Member merber3 = new Member("member3", 30, teamB);
        Member merber4 = new Member("member4", 40, teamB);

        em.persist(merber1);
        em.persist(merber2);
        em.persist(merber3);
        em.persist(merber4);

        // 초기화
        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.team = " + member.getTeam());

        }
    }
}

+ Recent posts