대머리개발자

querydsl로 마이그레이션 본문

개발이야기/DataBase

querydsl로 마이그레이션

대머리개발자 2024. 3. 7. 13:04
728x90

 

nativeQuery로 작성된 쿼리를 querydsl 형태로 변경하고자 한다.

 

why? 

새로운 기획요건에 대응이 안 된다. 

 

물론 새로운 end-point로 만들면 되는데 기존 쿼리에 단순 조건절 추가임에도 중복 코드가 산더미처럼 만들어진다.

물론 mybatis로 했으면 고민도 안 했을테쥐...

 

 

## 고민의 포인트는 아래 두가지에 대한 클린 쿼리 작성

 

1. 통계 데이터 조인을 How -> querydsl (방법상)

left outer join (
    select targetId,
         SUM(if(type = 0,  1, 0) ) as viewCount
        ,SUM(if(type = 1,  1, 0) ) as goodCount
from  countstat c group by targetId

 

 

2. 각종 서브쿼리를 조인쿼리로 변경. (성능상)

select
...
, ifnull(viewCnt, 0) viewCount
, ifnull(goodCnt,0) goodCount  
, (select count(1) replayCount from comment where comment.boardId = Board.id and status = 0 )   replayCount
, ifnull((select 1 from auth where boardId = board.id and userId = :userId and accessibleDt >= sysdate() ), 0) auth
...

 

 

## 그리고 querydsl로 변경!

,QCountStat.countStat.type.`when`(CountType.VIEW).then(1).otherwise(0).sum().`as`("viewCount")
,QCountStat.countStat.type.`when`(CountType.GOOD_BOARD).then(1).otherwise(0).sum().`as`("goodCount")

...
.leftJoin(QComment.comment).on(QComment.comment.boardId.eq(qBoard.id))
.leftJoin(QCountStat.countStat).on(QCountStat.countStat.targetId.eq(qBoard.id))

...

.groupBy(QBoard.board.id)

 

생각보다 처리가 깔끔했다.

 

프로젝트를 새롭게 구성할 때 이제는 거의 mybatis는 배제하고 진행하는 것 같다.

그 동안 고마웠어!

 

스트럿츠2를 보내고 스프링으로 넘어가는 느낌이다. 자연스럽게 ㅎ

 

 

728x90

'개발이야기 > DataBase' 카테고리의 다른 글

json vs 확장속성  (0) 2024.03.08
DB 꽃은 튜닝이지!  (0) 2024.03.07
평생 개발 공부를 해야하는 이유  (0) 2024.02.19
이벤트 참여자 무작위 추첨  (0) 2024.02.06
redisson 아직은...  (0) 2024.02.01