[Spring] 인터넷 강의 클론 6 - 검색 필터링

춤인형의 개발일지·2025년 2월 21일

Spring실습

목록 보기
33/40

요구사항

  • 강의 제목으로 검색 가능
  • 강사 이름으로 검색 가능
  • 검색 시 추가로 카테고리 가능

검색 필터링

검색같은 경우에 가장 많이 사용하는게 QueryDsl이다.

public List<Lecture> findAll(String title, String teacherName, Category category){
        return jpaQueryFactory
                .selectFrom(lecture)
                .join(lecture.teacher).fetchJoin()
                .where(
                        lecture.deleted.isFalse(),
                        lecture.isPrivate.isFalse(),
                        containsTitle(title),
                        containsTeacherName(teacherName),
                        containsCategory(category))
                .orderBy(
                        lecture.createTime.desc(),
                        lecture.countStudent.desc())
                .fetch();
    }

    private BooleanExpression containsCategory(Category category) {
        return (category == null) ? null : lecture.category.eq(category);
    }

    public BooleanExpression containsTitle(String title){
        return (title == null || title.isEmpty()) ? null : lecture.title.containsIgnoreCase(title);
    }

    public BooleanExpression containsTeacherName(String teacherName){
        return (teacherName == null || teacherName.isEmpty()) ? null : lecture.teacher.name.containsIgnoreCase(teacherName);
    }

삼항 연산자를 사용하면 아주 편하다 근데 가독성이 떨어지면 많이 사용하지 않는다고 한다. 근데 지금 내 코드에서는 그렇게 가독성을 요구할건 아닌 것 같아서 작성해도 될 것 같다.

containsIgnoreCase 대소문자 구분 없이 그냥 java만 검색해도 java관련된 모든 강의들이 나온다. 이런식..? 별거 없음!

중요한건 Controller이다!

Controller

//강의 목록 조회
    @GetMapping("/lectures")
    public List<LectureListResponse> readAll(@RequestParam(required = false) String title,
                                             @RequestParam(required = false) String teacherName,
                                             @RequestParam(required = false) Category category){
        return lectureService.findAll(title, teacherName,category);
    }

queryDsl을 사용하면 @RequestParam을 작성하게 되는데 그냥 작성해주면 무조건 들어와야한다는걸로 인식한다. 왜냐하면 기본적으로 코드 구조가 @RequestParam(required = true) 이기 때문에 무조건 들어와야한다. 하지만 우리는 이거일 때도 되고, 저거 일때도 되니까 @RequestParam(required = false)로 바꿔주면 된다

0개의 댓글