[spring boot 개발] DB에서 원하는 데이터 불러오기

이경민·2022년 7월 25일
0

spring

목록 보기
6/20

spring boot를 사용하여 특정 조건을 만족하는 데이터를 mysql에서 불러오기

Spring Boot 코드

Controller

@ResponseBody
@GetMapping("/recommend/{page}/{perPage}")
public BaseResponse<List<GetRecommendSupportConditionsRes>> getRecommendSupportConditionsRes(
 @PathVariable("page")int page, @PathVariable("perPage")int perPage       
 @RequestParam int age, @RequestParam int income_range, @RequestParam int gender, @RequestParam String area,
 @RequestParam(value = "personalArray") int[] personalArray,
 @RequestParam(value = "householdslArray") int[] householdslArray){
        
    try{
        List<GetRecommendSupportConditionsRes> getRecommendSupportConditionsRes = supportConditionsProvider.getRecommendSupportConditions(page, perPage, age, income_range, gender, area, personalArray, householdslArray);
            return new BaseResponse<>(getRecommendSupportConditionsRes);
        }catch (BaseException exception){
            logger.error("Error", exception);
            return new BaseResponse<>((exception.getStatus()));
        }
    }
}

Get 방식을 사용

@GetMapping

@PathVariable

@PathVariable ("page")int page: url의 /recommend/{page}/{perPage} 경로에서 페이지 지정

@RequestParam

@RequestParam int age: /recommend/{page}/{perPage} 경로 뒤에 ? 이후 age=1 과 같은 방식으로 age 지정

  • PathVariable 뒤에 ?를 붙여서 사용
  • RequestParam끼리는 &로 구분
  • 배열을 받아 올 때: @RequestParam(value="배열이름") int[] 배열이름 사용

url 예시

http://localhost:8080/supportConditions/recommend/1/10?age=50&income_range=100&gender=0&area=seoul&personalArray=0,0&householdslArray=0,0


DAO

// 추천 정책
public List<GetRecommendSupportConditionsRes> getRecommendSupportConditions(int page, int perPage, int age, int income_range, int gender, String area, int[]  personalArray, int[] householdslArray){

	// 소득분위 판단
    String income_query="";
	if (0<=income_range && income_range<=50) {             // JA0201
        income_query = " JA0201='Y'";
    } else if (51<=income_range && income_range<=75) {     // JA0202
        income_query = " JA0202='Y'";
    } else if (76<=income_range && income_range<=100) {    // JA0203
        income_query = " JA0203='Y'";
    } else if (101<=income_range && income_range<=200) {   // JA0204
        income_query = " JA0204='Y'";
    } else  {                                              // JA0205
        income_query = " JA0205='Y'";
    }

    // 성별 판단
    String gender_query="";
    if (gender==0) {               // 여성
        gender_query="JA0102 ='Y'";
    } else if (gender==1) {        // 남성
        gender_query="JA0101 ='Y'";
    }

    // 개인 특성
    String personal_query=" ";
    int count1=0;
    for (int a: personalArray) {
        count1=count1+1;
        if (a==0) {
            int idx=300+count1;
            if (idx==321) {
                idx=idx+1;
            }
            personal_query=personal_query.concat("OR JA0"+idx+" = 'Y' ");
        }    
     }

     // 가구 특성
     String households__query=" ";
     int count2=0;
     for (int a: personalArray) {
         count2=count2+1;
         if (a==0) {
             int idx=400+count2;
             if (idx==405) {
                 idx=idx+5;
             }
             personal_query=personal_query.concat("OR JA0"+idx+" = 'Y' ");
         }
     }

     String getRecommendServiceQuery3="select * from supportConditions where JA0110 <= "+age+" AND JA0111 >= "+age+
                " AND "+income_query+" AND "+gender_query+" limit " + perPage +" offset "+ (page-1)*perPage;

     return this.jdbcTemplate.query(getRecommendServiceQuery3,
             (rs, rowNum) -> new GetRecommendSupportConditionsRes(
                     rs.getString("SVC_ID"),
                     rs.getString("JA0101"),    // 남성
                     rs.getString("JA0102"),    // 여성

                     rs.getString("JA0110"),     // 대상 연령 시작
                     rs.getString("JA0111")      // 대상 연령 종료
              ));
 }

return 값

해당 내용은 json 형태로 전달한다. 이 내용은 postman에서 확인 가능하다


Provider

// 추천 정책 조회
public List<GetRecommendSupportConditionsRes> getRecommendSupportConditions(int page, int perPage, int age, int income_range, int gender, String area, int[] personalArray, int[] householdslArray) throws BaseException{
    try{
        List<GetRecommendSupportConditionsRes> getRecommendSupportConditionsRes = supportConditionsDao.getRecommendSupportConditions(page, perPage, age, income_range, gender, area, personalArray, householdslArray);
        return getRecommendSupportConditionsRes;
    }catch (Exception exception){
        throw new BaseException(DATABASE_ERROR);
    }
}

Res

@Getter
@Setter
@AllArgsConstructor
public class GetRecommendSupportConditionsRes {
    private String SVC_ID;
    private String JA0101;    // 남성
    private String JA0102;    // 여성

    private String JA0110;    // 대상 연령 (시작)
    private String JA0111;    // 대상 연령 (종료)
}

return하는 json의 내용들의 변수와 getter, setter 생성.


API 명세서

Request

NameTypeDescriptionExampleRequired
ageInt사용자의 나이 입력23Y
income_rangeInt사용자의 소득 분위 입력100Y
genderint사용자의 성별 입력 (0은 여성, 1은 남성)0Y
areastring사용자의 거주지 입력Y
personalArrayint[]‘Y’는 0, 아닌 경우는 1
개인 특성을 순서대로 입력 (총 26개)0,0,…Y
householdslArrayint[]‘Y’는 0, 아닌 경우는 1
가구 특성을 순서대로 입력 (총 9개)0,0,…Y

개인 특성

가구 특성

Response

NameTypeDescriptionExampleRequired
isSuccessBoolean요청 성공 여부trueY
codeInt응답 코드1000Y
messageString응답 메시지요청에 성공하였습니다.Y
resultList응답 리스트Y

result/

NameTypeDescriptionExampleRequired
ja0110String대상연령(시작)
ja0111String대상연령(종료)
ja0101String남성
ja0102String여성
svc_IDString정책 서비스 번호119200000163

응답 코드

codeDescription
1000성공
4000데이터베이스 에러

Response (Sample)

{
    "isSuccess": true,
    "code": 1000,
    "message": "요청에 성공하였습니다.",
    "result": [
        {
            "svc_ID": "000000465790",
            "ja0101": "Y",
            "ja0102": "Y",
            "ja0110": "3",
            "ja0111": "5"
        },
        {
            "svc_ID": "105100000001",
            "ja0101": "Y",
            "ja0102": "Y",
            "ja0110": "18",
            "ja0111": "65"
        },
        {
            "svc_ID": "119200000001",
            "ja0101": "Y",
            "ja0102": "Y",
            "ja0110": "18",
            "ja0111": "120"
        },
        {
            "svc_ID": "119200000012",
            "ja0101": "Y",
            "ja0102": "Y",
            "ja0110": "18",
            "ja0111": "65"
        },
        {
            "svc_ID": "119200000023",
            "ja0101": "Y",
            "ja0102": "Y",
            "ja0110": "18",
            "ja0111": "120"
        },
        {
            "svc_ID": "119200000024",
            "ja0101": "Y",
            "ja0102": "Y",
            "ja0110": "18",
            "ja0111": "120"
        },
        {
            "svc_ID": "119200000044",
            "ja0101": "Y",
            "ja0102": "Y",
            "ja0110": "18",
            "ja0111": "120"
        },
        {
            "svc_ID": "119200000045",
            "ja0101": "Y",
            "ja0102": "Y",
            "ja0110": "18",
            "ja0111": "120"
        },
        {
            "svc_ID": "119200000056",
            "ja0101": "Y",
            "ja0102": "Y",
            "ja0110": "18",
            "ja0111": "120"
        },
        {
            "svc_ID": "119200000059",
            "ja0101": "Y",
            "ja0102": "Y",
            "ja0110": "18",
            "ja0111": "120"
        }
    ]
}

0개의 댓글