inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

실전! Querydsl

querydsl dto mapping & subquery 질문 남깁니다.

3212

김준엽

작성한 질문수 9

0

안녕하세요 열심히 수업듣고 따라하고있는 수강생입니다.

먼저 매번 답변주셔서 감사합니다.

 

질문으로는 dto mapping 에서 @queryprojection 으로 직접 조회를 해야하는 상황입니다.

글 : 채팅방 1 : N

채팅방 : 채팅 1: N

일때

 

DTO 는


@Data
public class QChatRoomDto {
    private QaType qaApart;
    private String qaContent;
    private String searchPlace;
    private String category;
    private Long chooseMemberIdx; // 채택 / 미채택 기준
    private Long roomIdx;
    private Long otherMemberIdx;
    private String otherMemberNickname;
    private String otherMemberImgDto;
    private int qaCount;
    private String modifiedDate;
    private String recentlyMsg;
    private String recentlyMsgType;
    private Long notReadCount;

    @QueryProjection
    public QChatRoomDto(String qaContent, String searchPlace, String category, Long chooseMemberIdx, Long roomIdx, Long otherMemberIdx, String otherMemberNickname, String otherMemberImgDto, int qaCount, LocalDateTime modifiedDate, String recentlyMsg, String recentlyMsgType, Long notReadCount) {
        this.qaApart = QUESTION;
        this.qaContent = qaContent;
        this.searchPlace = searchPlace;
        this.category = category;
        this.chooseMemberIdx = chooseMemberIdx;
        this.roomIdx = roomIdx;
        this.otherMemberIdx = otherMemberIdx;
        this.otherMemberNickname = otherMemberNickname;
        this.otherMemberImgDto = otherMemberImgDto;
        this.qaCount = qaCount;
        this.modifiedDate = modifiedDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        this.recentlyMsg = recentlyMsg;
        this.recentlyMsgType = recentlyMsgType;
        this.notReadCount = notReadCount;
    }
}

 

querydsl

public Page<QChatRoomDto> myQuestionChatRoomList(Member questionMember, List<Member> blockMembers, QaStatusType qaStatusType, Pageable pageable) {
    return applyPagination(pageable, contentQuery -> contentQuery
            .selectDistinct(new QQChatRoomDto(
                            qa.content.as("qaContent"),
                            qa.searchPlace.as("searchPlace"),
                            qa.category.name.as("category"),
                            qa.selectMember.idx.as("chooseMemberIdx"),
                            chatRoom.idx.as("roomIdx"),
                            chatRoom.aMember.idx.as("otherMemberIdx"),
                            chatRoom.aMember.nickname.as("otherMemberNickname"),
                            chatRoom.aMember.memberImg.as("otherMemberImgDto"),
                            chatRoom.qMember.qaList.size().as("qaCount"),
                            chatRoom.modifiedDate.as("modifiedDate"),
                            ExpressionUtils.as(
                                    JPAExpressions.select(chat.content)
                                            .from(chat)
                                            .where(chat.chatRoom.eq(chatRoom),
                                                    chat.idx.eq(
                                                            JPAExpressions.select(chat.idx.max())
                                                                    .from(chat))
                                            ), "recentlyMsg")
                            ,
                            ExpressionUtils.as(
                                    JPAExpressions.select(chat.chatType)
                                            .from(chat)
                                            .where(chat.chatRoom.eq(chatRoom),
                                                    chat.idx.eq(
                                                            JPAExpressions.select(chat.idx.max())
                                                                    .from(chat))
                                            ), "recentlyMsgType"),
                            ExpressionUtils.as(
                                    JPAExpressions.select(chat.count())
                                            .from(chat)
                                            .where(chat.chatRoom.eq(chatRoom),
                                                    chat.member.ne(questionMember),
                                                    chat.readMsg.isFalse()), "notReadCount")
                    )
            )
            .from(chatRoom)
            .join(chatRoom.qa, qa)
            .join(chatRoom.aMember, member)
            .where(chatRoom.qMember.eq(questionMember),
                    isQaSelectMember(questionMember, qaStatusType),
                    blockAMembersNotIn(blockMembers),
                    chatRoom.idx.notIn(
                            JPAExpressions.select(chatRoom.idx)
                                    .from(chatRoom)
                                    .where(chatRoom.isLeave.contains("_" + questionMember.getIdx() + "_"))),
                    member.phoneNum.isNotNull()
            )
            .orderBy(chatRoom.modifiedDate.desc()));
}

이렇게 작업을 했습니다. 매우 이상한 쿼리이겠지만 저한텐 이게 최선이었습니다 ㅠ

여기서 궁금한점은 채팅룸 리스트를 뽑아야 하는데

recentlyMsg, recentlyMsgType

채팅 리스트의 최근 데이터를 가지고 오고싶었으나

subQuery에서 limit 1 이 먹히지 않아

저런 괴랄한? 쿼리를 만들어 작동은 되게 만들었습니다.

 

해서 dto mapping 할때 컬렉션 리스트를 뽑는 다른 방법이 있는지 궁금합니다.

chatRoom.chatlist 를 반환하여 queryprojection에서 가공하려 했지만

에러가 뜨면서 chatList는 반환이 안되어 질문글 남깁니다.

 

감사합니다.

 

java JPA

답변 1

1

김영한

안녕하세요. 김준엽님

DTO Mapping의 경우 데이터를 한줄로 풀어서 조회하게 됩니다. 따라서 컬렉션 리스트를 뽑는 것은 어렵습니다.

추가로 너무 복잡한 쿼리의 경우 네이티브 쿼리나, JdbcTemplate으로 SQL을 직접 사용하는 것을 권장드립니다.

감사합니다.

0

김준엽

답변 감사합니다.

SpringBoot 4.X에서의 Querydsl 설정

0

107

2

querydsl 오픈소스에 대한 질문

1

83

1

예제에서의 카운트 쿼리에서 join문과 where문은 필요없지 않나요?

0

115

1

Querydsl 6.X버전에 대해서 어떻게 생각하시나요?

0

328

2

여러 테이블 조인하여 통계치를 구하고자 할 때 어떤 방법이 더 효율적일까요

1

73

1

fetchResults()는 더이상 권장되지 않는다는데 맞나요?

0

164

1

querydsl sum() 메서드 없어요.

0

163

2

build 디렉터리 생성

0

142

2

자바 ORM 표준 JPA 프로그래밍 - 기본편 듣고 바로 학습해도 괜찮을까요?

0

116

2

현재 Querydsl에서 from절 서브쿼리를 지원하나요?

0

95

1

오타 제보 드립니다.

0

74

2

벌크 연산과 flush, clear

0

78

1

Run As Intellij 로 변경시 Q타입 import 불가

0

90

1

QHello import하기 문제 발생

0

150

2

등록된 함수 보는법(H2Dialect) 질문

0

70

2

5.0부터 Querydsl은 향후 fetchCount() , fetchResult() 를 지원하지 않기로 결정했다고 하는데 이에 맞는 강의

1

201

2

[환경설정 PDF 부트 3.0이후 설명 질문] build.gradle에 compileQuerydsl을 정의하지 않은 상태에서 Gradle->Tasks->other->compileQuerydsl을 클릭하라고 하는 이유가 무엇인가요??

1

204

1

querydsl 설정 문제

0

223

2

quey dsl 설정부분

0

159

2

count 쿼리 관련 질문입니다!

0

75

1

stringtemplate를 이용하여 where절 검색 방법 질문 드립니다.

0

90

1

답변부탁드리겠습니다.

0

91

2

(OrderSpecifier)관련 내용 어디있을가요

0

67

1

중급문법 벌크연산에서

0

84

2