스프링데이터 + JPA/QueryDSL

6. 예제 도메인 모델

sdafdq 2023. 11. 28. 08:10

https://qwefdg3.tistory.com/869

 

이거랑 똑같은 거 할거임.

 

@Entity
@Getter @Setter(AccessLevel.PRIVATE)
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@ToString(of={"id", "username", "age"})
public class Member{
    @Id @GeneratedValue
    @Column(name="member_id")
    private Long id;

    @Setter(AccessLevel.PUBLIC)
    private String username;
    private int age;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "team_id")
    private Team team;

    public Member(String username, int age, Team team) {
        this.username = username;
        this.age = age;
        if(team != null){
            changeTeam(team);
        }
    }
    public Member(String username, int age) {
        this.username = username;
        this.age = age;
    }
    public Member(String username) {
        this.username = username;
    }

    public void changeTeam(Team team){
        this.setTeam(team);
        team.getMembers().add(this);
    }

}

 

 

 

@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;
    }
}

 

 

@SpringBootTest
@Transactional
@Commit
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> result = em.createQuery("select m from Member m", Member.class)
                .getResultList();

        for (Member member : result) {
            System.out.println("member = " + member);
            System.out.println("team = " + member.getTeam());
        }
    }

}

테스트

'스프링데이터 + JPA > QueryDSL' 카테고리의 다른 글

8. Q타입  (0) 2023.11.28
7. JPQL vs QueryDSL  (0) 2023.11.28
5. H2 DB 설치 및 설정  (0) 2023.11.27
4. 연관 라이브러리  (0) 2023.11.27
3. QueryDSL 설정  (0) 2023.11.27