jsonpath: JSONPath는 JSON 객체의 요소를 쿼리하는 표준화된 방법으로 경로 표현식을 사용하여 JSON 문서에서 요소, 중첩된 요소 및 배열을 탐색할 수 있다.
spring-boot2.5.6 사용 시 자동으로 들어있는 com.jayway.jsonpath:json-path 라이브러리를 사용한다.
사용 예: 디비의 extraData 콜롬의 값이 string json 이고, 그 json 안에서 쿼리를 날려야 할 경우
@Query(value = "select round," +
" sum(money) as totalMoney," +
" sum(lua) as totalLua," +
" sum(ticket) as totalTicket, " +
" sum(stuff) as totalStuff, " +
" sum(emoticon) as totalEmoticon " +
"from (" +
" select l.extra_data->>'$.week' round" +
" , if (item_type = 1, l.cnt, 0) money" +
" , if (item_type = 2, l.cnt, 0) lua" +
" , if (item_type = 3, l.cnt, 0) ticket" +
" , if (item_type = 6, l.cnt, 0) stuff" +
" , if (item_type = 7, l.cnt, 0) emoticon" +
" from table_l as l" +
" where event_id = 'aaa'" +
") as h" +
" group by h.round",
nativeQuery = true)
위 쿼리에서
l.extra_data->>'$.week' round
의 의미를 알아보자면
1. table_l 에는 extra_data 라는 콜롬이 있고, 그 내용은 {week:1, level:0} 이런 형식으로 생겼다.
2. mysql ->> operator는 unquote를 해준다('1' 로 나올 데이터를 1로 바꿔준다)
https://dev.mysql.com/doc/refman/5.7/en/json-search-functions.html#operator_json-inline-path
MySQL :: MySQL 5.7 Reference Manual :: 12.18.3 Functions That Search JSON Values
12.18.3 Functions That Search JSON Values The functions in this section perform search operations on JSON values to extract data from them, report whether data exists at a location within them, or report the path to data within them. JSON_CONTAINS(target,
dev.mysql.com
3. 그 결과를 round라는 이름으로 꺼내온다(alias).
json의 형식으로 든 디비 데이터를 쿼리에서 꺼내서 사용할 때 유용할 듯 하다.
다른 이야기. 후에 비슷한 캐이스가 발생하여 있어서 추가로 남긴다.
작동되는 버전
@Query(value = "select " +
"JSON_EXTRACT(data, '$.clazz') as clazz, "+
"JSON_EXTRACT(data, '$.totalScore') as totalScore "+
"from hd_user_event e " +
"where e.gid = :gid " +
"and e.event_id = 'CoolTimeEvent' " +
"order by e.base_date desc ",
nativeQuery = true)
Stream<DoubleWheelUserRes> getDoubleWheelUserInfoList(String gid, Pageable pageable);
아래처럼 nativeQuery = false로 해서 바로 pojo로 바꾸고 싶었는데, 절대 불가였다..ㅠㅠ
그 이유는 jpql로 db function을 가져올 방법이 없었음.. 아래와 같이 하고 실행하면 Jqpl validation fail 이라고 뜨면서 실행불가다.. 아쉽.. 그래서 결국 native query true로 주고 DoubleWheelUserRes을 projection로 만들어서 해결했다..
참고) 작동 안되는 버전
@Query(value = "select new com.model.event.DoubleWheelUserRes( " +
"function('JSON_EXTRACT', e.data, '$.clazz'), "+
"function('JSON_EXTRACT', e.data, '$.totalScore') "+
") from UserEvent e " +
"where e.gid = :gid " +
"and e.eventId = 'CoolTimeEvent' " +
"order by e.baseDate desc "
)
참고:
https://www.lesstif.com/dbms/mysql-json-data-54952420.html
MySQL 에서 JSON Data사용하기
www.lesstif.com
https://www.lesstif.com/dbms/jsonpath-54952418.html
JSONPath 사용법
www.lesstif.com
'개발 > sql' 카테고리의 다른 글
[mysql] 유저의 등수 구하기 rank under v8 (0) | 2024.02.06 |
---|---|
[DB] 분산환경에서 데이터 저장소 선택과 활용 (0) | 2023.07.24 |
[형상관리] flyway vs liquibase (0) | 2022.07.08 |
[sql] case vs if (0) | 2022.05.02 |
[sql] aggregate / window function(mysql) (0) | 2022.05.02 |