Json파일을 db에 넣기-test
우리가 가지고 있는 api에서 호출했을때 과연 json파일이 잘 저장될까 의문이었다.
kafka로 produce/consume을 하기전에 실제 db에 json파일이 저장되는데 문제가 없는지 test를 해보았다.
소스코드 및 과정
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Entity
@Table(name = "game_record_json")
public class GameRecordJson {
@Id
@GeneratedValue
@Column(name = "game_record_json_id")
private Long id;
@Column(name = "json", columnDefinition = "longtext")
@Lob
private String twentyGameRecord;
@Builder
public GameRecordJson(Long id, String twentyGameRecord) {
this.id = id;
this.twentyGameRecord = twentyGameRecord;
}
}
다음과 같이 @Lob을 사용하면 다음과 같은 특징이 있다.
@Lob
데이터베이스에서 VARCHAR보다 큰 데이터를 담고 싶을 때 사용한다.
특징
- 속성이 없다.
- 매핑하는 필드의 타입에 따라 DB의 BLOB, CLOB과 매핑된다.
- 문자열인 경우(String, char[], java.sql.CLOB): CLOB
- 그 외(byte[], java.sql.BLOB): BLOB
public interface GameRecordJsonRepository extends JpaRepository<GameRecordJson,Long> {
}
간단하게 GameRecordJsonRepository를 만든다. (test용도)
@Data
@NoArgsConstructor
public class GameRecordDto {
private JSONObject latestTwentyRecords;
private JSONArray gameRecord;
@Override
public String toString() {
return this.latestTwentyRecords.toString() + gameRecord.toString();
}
}
최종적인 json파일을 주는 dto를 toString를 재정의한다.
JSonObject와 JsonArray로 되어있기에 다음과 같이 재정의 해줘야함.
(인텔리제이 자동완성 쓰면 에러남)
@Parameter(name="lolName",description = "롤네임")
@GetMapping("user/gameRecord")
public ResponseEntity getTokenForGameRecord(@RequestParam(value = "lolName") String lolName) throws LolApiToJsonException, ParseException, org.json.simple.parser.ParseException, IOException {
GameRecordDto gameRecordDto = null;
gameRecordDto = gameRecordService.getGameRecord(lolName);
// try {
// gameRecordDto = gameRecordService.getGameRecord(lolName);
// } catch (Exception e) {
// throw new LolApiToJsonException("롤 api에 호출시 에러");
// }
GameRecordJson gameRecordJson = GameRecordJson.builder().twentyGameRecord(gameRecordDto.toString()).build();
gameRecordJsonRepository.save(gameRecordJson);
return new ResponseEntity(gameRecordDto, HttpStatus.OK);
}
save를 통해 db에 실제 json 데이터 적재
db결과
실제 db 조회
음 근데 왜 url에 \/가 생기지...
추후 해결해봐야 할 문제이다..
일단 긴 데이터도 저장되긴 한다!
추가 해결방안
https://hianna.tistory.com/632#jackson1
[Java] Jackson 라이브러리를 이용하여 Object를 JSON으로 변환하기
Java Object -> JSON 문자열 Java Object -> JSON 파일 Map -> JSON 문자열 List -> JSON 문자열 배열 -> JSON 문자열 Java Object를 JSON 문자열로 변환하기 위해서 Jackson ObjectMapper 의 다음 메소드를 사용..
hianna.tistory.com
'프로젝트 > 롤 전적검색 프로젝트' 카테고리의 다른 글
[롤 전적검색] NiFi&Kafka를 이용하여 Json 데이터를 RDMBS에 적재(2) (0) | 2022.09.28 |
---|---|
[롤 전적검색] NiFi&Kafka를 이용하여 Json 데이터를 RDMBS에 적재 (1) | 2022.09.26 |
RBMS에 JSON 적재하기(2) (0) | 2022.09.20 |
[DOCKER] react-docker시 unable to resolve dependency tree 문제 해결 (0) | 2022.09.16 |
[트러블 슈팅]라이엇api 호출 delay (0) | 2022.08.29 |