Notice
Recent Posts
Recent Comments
Link
«   2025/01   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

개발자되기 프로젝트

@Query, 값, DTO 조회하기 본문

인프런/[인프런] Spring Data JPA

@Query, 값, DTO 조회하기

Seung__ 2021. 8. 29. 15:09

1. 등록된 회원들의 이름을 조회


  • MemberRepository
@Query("select m.userName from Member m")
    List<String> findUserNameList();
  • Test
 @Test
    public void findUserNameList(){
        Member member1 = new Member("aaa", 10);
        Member member2 = new Member("bbb", 20);
        memberRepository.save(member1);
        memberRepository.save(member2);

        List<String> userNameList = memberRepository.findUserNameList();
        for (String userName : userNameList) {
            System.out.println("userName = " + userName);
        }

    }

 

 

2. Dto로 조회


  • MemberDto
@Data
public class MemberDto {

    private Long id;
    private String userName;
    private String teamName;

    public MemberDto(Long id, String userName, String teamName) {
        this.id = id;
        this.userName = userName;
        this.teamName = teamName;
    }
}
  • MemberRepository
    • 쿼리내에서 new를 통해 Dto를 생성하여 반환.
    •  
@Query("select new study.datajpa.dto.MemberDto(m.id, m.userName, t.name) from Member m join m.team t")
List<MemberDto> findMemberDto();
  • Test
    @Test
    public void findMemberDto(){
        Team team = new Team("teamA");
        teamRepository.save(team);

        Member member1 = new Member("aaa", 10);
        member1.changeTeam(team);
        memberRepository.save(member1);

        List<MemberDto> memberDtos = memberRepository.findMemberDto();

        System.out.println("========================");
        for (MemberDto memberDto : memberDtos) {
            System.out.println("memberDto = " + memberDto);
        }
    }

 

3.GitHub : 210829 @Query, Dto


 

 

GitHub - bsh6463/SpringDataJpa

Contribute to bsh6463/SpringDataJpa development by creating an account on GitHub.

github.com

 

'인프런 > [인프런] Spring Data JPA' 카테고리의 다른 글

@Query, 반환 타입  (0) 2021.08.29
@Query, 파라미터 바인딩  (0) 2021.08.29
@Query, repository method에 쿼리 정의  (0) 2021.08.28
JPA NamedQuery  (0) 2021.08.28
쿼리 메서드  (0) 2021.08.28
Comments