Notice
Recent Posts
Recent Comments
Link
«   2024/12   »
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
관리 메뉴

아님말고

[JPA] QueryDSL 조회시 원하는 컬럼만 가져오기 본문

JPA

[JPA] QueryDSL 조회시 원하는 컬럼만 가져오기

스타박씨 2022. 9. 14. 21:25

Member.java

@Data
@Entity
@Table(name = "member")
public class Member {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private int id;
	
	private String name;
	private String email;
}

 

MemberDTO.java

@Getter
public class MemberDTO {
	private String name;
	private String email;
	
	@QueryProjection
	public MemberDTO(String name, String email) {
		this.name = name;
		this.email = email;
	}
}

 

MemberRepository.java

public interface MemberRepository extends JpaRepository<Member, Integer>, MemberRepositoryCustom {

}

 

MemberRepositoryCustom.java

public interface MemberRepositoryCustom {

	List<MemberDTO> findByNameOrEmail(String type, String keyword);
}

 

MemberRepositoryCustomImpl.java

@RequiredArgsConstructor
public class MemberRepositoryCustomImpl implements MemberRepositoryCustom {

	private final JPAQueryFactory jpaQueryFactory;
	private final QMember qMember = QMember.member;
	
	@Override
	public List<MemberDTO> findByNameOrEmail(String type, String keyword) {
		
		List<MemberDTO> content = jpaQueryFactory
				.select(new QMemberDTO(qMember.name, qMember.email))
				.from(qMember)
				.where(qMember.email.contains(keyword))
				.fetch();
		return content;
	}
}

 

MemberController.java

@RestController
@RequiredArgsConstructor
public class MemberController {

	private final MemberRepository memberRepository;
	
	@GetMapping("members/search")
	public ResponseEntity<List<MemberDTO>> selectMemberByNameOrEmail(
			@RequestParam String type, 
			@RequestParam String keyword){
		List<MemberDTO> list = memberRepository.findByNameOrEmail(type, keyword);
		return ResponseEntity.ok(list);
	}
}
Comments