Spring Data JPA - 반환 타입

목차

반환 타입

List<Member> findListByUsername(String username); // 반환 타입 : 컬랙션
Member findMemberByUsername(String username); // 반환 타입 : 단건
Optional<Member> findOptionalByUsername(String useranme); // 반환 티입 : 단건 Optional
public interface MemberRepository extends JpaRepository<Member, Long> {
List<Member> findByUsernameAndAgeGreaterThan(String username, int age);

@Query("select m from Member m where m.username = :username and m.age = :age")
List<Member> findUser(@Param("username") String username, @Param("age") int age);

// 값으로 조회하기
@Query("select m.username from Member m")
List<String> findUsernameList();

// DTO로 조회하기
@Query("select new com.example.datajpa.dto.MemberDto( m.id, m.username, t.name)from Member m join m.team t")
List<MemberDto> findMemberByDto();

@Query("select m from Member m where m.username in :names")
List<Member> findByNames(@Param("names") Collection<String> names);

List<Member> findListByUsername(String username); // 반환 타입 : 컬랙션
Member findMemberByUsername(String username); // 반환 타입 : 단건
Optional<Member> findOptionalByUsername(String useranme); // 반환 티입 : 단건 Optional
}
@Test
public void returnType(){
Member member1 = new Member("AAA", 10);
Member member2 = new Member("BBB", 20);
memberRepository.save(member1);
memberRepository.save(member2);

List<Member> members = memberRepository.findListByUsername("AAA");
Member member = memberRepository.findMemberByUsername("AAA");
Optional<Member> optional = memberRepository.findOptionalByUsername("AAA");

assertThat(members).isInstanceOf(List.class);
assertThat(member).isInstanceOf(Member.class);
assertThat(optional).isInstanceOf(Optional.class);
}
Share