티스토리 뷰

이번에는 파싱한 데이터를 DB에 넣는 작업을 진행했어요.

 

컨트롤러

package com.codingrecipe.board.controller;

import com.codingrecipe.board.dto.MusicalDTO;

import com.codingrecipe.board.service.MusicalService;
import lombok.RequiredArgsConstructor;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;


@RestController
@RequiredArgsConstructor
public class MusicalController {

    private final MusicalService musicalService;


    @GetMapping("/api")
    public String load_save() throws IOException, ParseException {

        MusicalDTO musicalDTO = new MusicalDTO();

        StringBuilder urlBuilder = new StringBuilder("http://apis.data.go.kr/6260000/BusanCultureMusicalService/getBusanCultureMusical"); /*URL*/
        urlBuilder.append("?" + URLEncoder.encode("serviceKey","UTF-8") + "=BrjHJ90yRTyYUg5oXeTm2jkYZqSjX1PwSP7Deo4z9S1eZflecDH0maN6daAzOYp2Yrar15uGqecubtJ1%2Fh%2Fl7w%3D%3D"); /*Service Key*/
        urlBuilder.append("&" + URLEncoder.encode("pageNo","UTF-8") + "=" + URLEncoder.encode("1", "UTF-8")); /*페이지번호*/
        urlBuilder.append("&" + URLEncoder.encode("numOfRows","UTF-8") + "=" + URLEncoder.encode("10", "UTF-8")); /*한 페이지 결과 수*/
        urlBuilder.append("&" + URLEncoder.encode("resultType","UTF-8") + "=" + URLEncoder.encode("json", "UTF-8")); /*JSON방식으로 호출 시 파라미터 resultType=json 입력*/
        URL url = new URL(urlBuilder.toString());
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-type", "application/json");
        System.out.println("Response code: " + conn.getResponseCode());
        BufferedReader rd;
        if(conn.getResponseCode() >= 200 && conn.getResponseCode() <= 300) {
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        } else {
            rd = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
        }
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }
        rd.close();
        conn.disconnect();
        System.out.println(sb.toString());

        JSONParser parser = new JSONParser();
        JSONObject jsonObject = (JSONObject) parser.parse(sb.toString());

        // "getBusanCultureMusical" 객체에서 "item" 키에 해당하는 값 가져오기
        JSONObject getBusanCultureMusical = (JSONObject) jsonObject.get("getBusanCultureMusical");
        JSONArray items = (JSONArray) getBusanCultureMusical.get("item");

        // 아이템 배열을 순회하며 각 아이템을 처리하고 저장
        for (Object itemObject : items) {
            JSONObject itemJson = (JSONObject) itemObject;

            // 각 아이템의 필드 가져오기
            String res_no = (String) itemJson.get("res_no");
            String title = (String) itemJson.get("title");
            String op_st_dt = (String) itemJson.get("op_st_dt");
            String op_ed_dt = (String) itemJson.get("op_ed_dt");
            String op_at = (String) itemJson.get("op_at");
            String place_nm = (String) itemJson.get("place_nm");
            String pay_at = (String) itemJson.get("pay_at");

            musicalDTO.setRes_no(res_no);
            musicalDTO.setTitle(title);
            musicalDTO.setOp_st_dt(op_st_dt);
            musicalDTO.setOp_ed_dt(op_ed_dt);
            musicalDTO.setOp_at(op_at);
            musicalDTO.setPlace_nm(place_nm);
            musicalDTO.setPay_at(pay_at);

            System.out.println(musicalDTO);
            musicalService.save(musicalDTO);
           
        }

        return sb.toString();
    }









}

 

DTO

package com.codingrecipe.board.dto;


import lombok.*;

@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class MusicalDTO {

    private String res_no;
    private String title;
    private String op_st_dt;
    private String op_ed_dt;
    private String op_at;
    private String place_nm;
    private String pay_at;

}

 

Entity

package com.codingrecipe.board.entity;

import com.codingrecipe.board.dto.MusicalDTO;
import lombok.Getter;
import lombok.Setter;

import javax.persistence.*;

@Entity
@Table(name = "musical_table")
@Setter
@Getter
public class MusicalEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY) //auto_increment
    private Long res_no;

    @Column
    private String title;
    @Column
    private String op_st_dt;
    @Column
    private String op_ed_dt;
    @Column
    private String place_nm;
    @Column
    private String op_at;
    @Column
    private String pay_at;


    public static MusicalEntity toSaveEntity(MusicalDTO musicalDTO) {
        MusicalEntity musicalEntity = new MusicalEntity();

        musicalEntity.setOp_at(musicalDTO.getOp_at());
        musicalEntity.setTitle(musicalDTO.getTitle());
        musicalEntity.setPay_at(musicalDTO.getPay_at());
        musicalEntity.setOp_ed_dt(musicalDTO.getOp_ed_dt());
        musicalEntity.setOp_at(musicalDTO.getOp_at());
        musicalEntity.setOp_st_dt(musicalDTO.getOp_st_dt());

        return musicalEntity;

    }
}

 

repository

package com.codingrecipe.board.repository;

import com.codingrecipe.board.entity.CommentEntity;
import com.codingrecipe.board.entity.MusicalEntity;
import org.springframework.data.jpa.repository.JpaRepository;

public interface MusicalRepository extends JpaRepository<MusicalEntity, Long> {
}

 

Service

package com.codingrecipe.board.service;

import com.codingrecipe.board.dto.MusicalDTO;
import com.codingrecipe.board.entity.MusicalEntity;
import com.codingrecipe.board.repository.MusicalRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class MusicalService {
    private final MusicalRepository musicalRepository;

    public void save(MusicalDTO musicalDTO){
        MusicalEntity musicalEntity = MusicalEntity.toSaveEntity(musicalDTO);
        musicalRepository.save(musicalEntity);

    }
}

 

 

DB 설계하는 방식은 이 분 유튜브 참고하면 좋을거 같아요.

저는 mysql은 익숙하지 않아서 밑에 코딩레시피 유튜버님의 방식을 참고해서 만들었어요.

 

DTO를 Entity로 변환하는 작업을 진행 후 JPA로 데이터를 저장했어요. 

(9) 코딩레시피 - YouTube

 

코딩레시피

요리 레시피를 따라하듯 코딩도 쉽게!! 따라해보면서 코딩 결과물을 만들어 봅시다!! 스프링부트, 스프링프레임워크로 게시판을 만들어봅시다. 설치나 세팅 관련은 블로그에 정리하고 있습니다

www.youtube.com

 

 

결과

 

 

 

 

드디어 데이터 넣는게 끝났네요. 

막히고 에러 나올때는 너무 힘든데

원하는 결과가 나왔을때는 도파민 뿜뿜이라 너무 좋네요!!

 


저번 작성글

 

공공데이터포탈 Open API 사용법 1. (데이터 불러오기) — 파이네 개발일지 (tistory.com)

 

공공데이터포탈 Open API 사용법 1. (데이터 불러오기)

일단 공공데이터포탈에 접속을 합니다. 원하는 제목의 오픈 API에 들어가서 활용신청을 해주세요 저는 부산광역시_뮤지컬 목록 서비스을 했어요. 활용신청을 하는건 간단해요 원하는 API에 들어

paine.tistory.com

공공데이터포탈 Open API 사용법 2. (데이터 파싱하기) JAVA — 파이네 개발일지 (tistory.com)

 

공공데이터포탈 Open API 사용법 2. (데이터 파싱하기) JAVA

XML로 데이터를 확인했으니 이제 이거를 활용할 준비를 해볼까요? 컨트롤러에 데이터를 들고 올 수 있도록 작업을 시작할께요. 데이터 신청한 곳에 들어가면 상세설명 버튼이 있을꺼에요. 밑으

paine.tistory.com

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2026/02   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
글 보관함