@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, int age){
this(username,age,null);
}
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);
}
}
@Entity
@Getter
@Setter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@ToString(of={"id","name"})
public class Team {
@Id @GeneratedValue
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이다.
주의점은 toString을 만들 때 연관관계가 있는 필드를 넣어버리면 무한루프를 타면서 오류가 날 수 있어서 가급적이면 소유한 필드만 toString에 넣고 연관관계 필드는 넣지 않는게 좋다.
@SpringBootTest
@Transactional
class MemberTest {
@Autowired
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,teamB);
Member member4 = new Member("member4",40,teamB);
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.team = " + member.getTeam());
}
}
}
em.flush
: 영속성 컨텍스트에 있는 엔티티들을 쿼리를 날려 db에 반여한다.
em.clear
: 영속성 컨텍스트를 깔끔하게 초기화한다
쿼리를 보기 위해 이렇게 해준다.
db에서 결과를 보고 싶으면 @Commit
애노테이션을 달아주면 된다.