인프런 커뮤니티 질문&답변

nhkwak71님의 프로필 이미지

작성한 질문수

스프링 DB 2편 - 데이터 접근 활용 기술

자바 언어에 대한 근본적인 질문...

23.09.12 18:57 작성

·

325

·

수정됨

0

안녕하세요. 스프링과 mybatis를 이용하여 프로젝트를 이용하여 프로젝트를 하고 있습니다.

Controller.java

@ApiOperation(value = "알람 정보 조회")
@GetMapping("/alarm")
public AlarmSearchResponseDTO alarmList(
        @RequestParam(required = false) String siteName,
        @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") LocalDateTime startTime,
        @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") LocalDateTime endTime,
        @RequestParam(required = false) String cameraName,
        @RequestParam(required = false) String accidentType,
        @RequestParam(required = false) String modelVersion,
        @RequestParam(required = false) String action,
        @RequestParam(required = false) String sortColumn,
        @RequestParam(required = false) String sortType,
        @RequestParam(required = false) Integer pageNum,
        @RequestParam(required = false) Integer pageSize {
    AlarmSearchConditionDTO alarmSearchConditionDTO = AlarmSearchConditionDTO.builder()
            .siteName(siteName)
            .cameraName(cameraName)
            .startTime(startTime)
            .endTime(endTime)
            .cameraName(cameraName)
            .accidentType(accidentType)
            .modelVersion(modelVersion)
            .action(action)
            .sortColumn(sortColumn)
            .sortType(sortType)
            .pageNum(pageNum)
            .pageSize(pageSize)
            .build();

    return aiBoxService.selectAlarmInfo(alarmSearchConditionDTO);
}

 

AlarmSearConditionDTO.java

@Data
@NoArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class AlarmSearchConditionDTO extends requestPaging {

    @ApiModelProperty(notes = "현장명", example = "현장명")
    private String siteName;

    @ApiModelProperty(notes = "발생 일시", example = "발생 일시")
    @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss")
    private LocalDateTime startTime;

    @ApiModelProperty(notes = "종료 일시", example = "종료 일시")
    @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss")
    private LocalDateTime endTime;

    @ApiModelProperty(notes = "카메라번호", example = "카메라 번호")
    private String cameraName;

    @ApiModelProperty(notes = "안전사고 유형", example = "안전사고 유형")
    private String accidentType;

    @ApiModelProperty(notes = "모델버전", example = "알람 코드")
    private String modelVersion;

    @ApiModelProperty(notes = "요청 사항", example = "요청 사항")
    private String action;

    @ApiModelProperty(notes = "정렬 기준", example = "정렬 기준")
    private String sortColumn;

    @ApiModelProperty(notes = "정렬 기준", example = "정렬 기준")
    private String sortType;

    @ApiModelProperty(notes = "페이징", example = "페이징")
    private requestPaging paging;


    @Builder
    public AlarmSearchConditionDTO(String siteName, LocalDateTime startTime, LocalDateTime endTime, String cameraName,
                                   String accidentType, String modelVersion, String action, String sortColumn, String sortType, Integer pageNum, Integer pageSize) { //pageNum, pageSize -> Integer
        this.siteName = siteName;
        this.startTime = startTime;
        this.endTime = endTime;
        this.cameraName = cameraName;
        this.accidentType = accidentType;
        this.modelVersion = modelVersion;
        this.action = action;
        this.sortColumn = sortColumn;
        this.sortType = sortType;

        if (pageNum != null && pageNum > 0) {
            this.paging = new requestPaging(pageNum, pageSize); // Both pageNum and pageSize provided, use them.
        } else if (pageSize != null && pageSize > 0) {
            this.paging = new requestPaging(null, pageSize); // pageSize provided, use it.
        } else {
            this.paging = new requestPaging(); // Default values.
        }
    }

requestPaging.java

@Data
@Slf4j
public class requestPaging {
//    pageNum, pageSize -> Integer
    private Integer pageNum;
    private Integer pageSize;
    private int totalPageCnt;

    public requestPaging() {
        this.pageNum = 1;
        this.pageSize = 30;
    }

//    pageNum, pageSize -> Integer
    public requestPaging(Integer pageNum, Integer pageSize) {
//        this.pageNum = (pageNum != null && pageNum > 0) ? pageNum : 1; // pageNum이 null이거나 0 이하일 경우 1을 기본값으로 사용
//        this.pageSize = (pageSize != null && pageSize > 0 && pageSize <= 100) ? pageSize : 30; // pageSize가 null이거나 0 이하 또는 100을 초과할 경우 30을 기본값으로 사용
        this.pageNum = (pageNum > 0) ? pageNum : 1;
        this.pageSize = (pageSize > 0 && pageSize <= 100) ? pageSize : 30; //
    }


    public int getStartPage() {
        return (pageNum-1) * pageSize;
    }

    public void setPage(int page) {
        this.pageNum = (page < 1) ? 1 :  page;
    }

    public void setPerPageNum(int perPageNum){
        if(perPageNum <= 0 || perPageNum > 100){
            this.pageSize= 30;
            return;
        }
        this.pageSize = perPageNum;
    }

    public int setTotalPageNum(int totalCnt){
        int total=0;
        if((totalCnt%pageSize)==0)total=totalCnt/pageSize;
        else total = (totalCnt / pageSize) + 1;
        return total;
    }

    public int getTotalPageCnt(){
        return totalPageCnt;
    }



}

Service.java

public AlarmSearchResponseDTO selectAlarmInfo(AlarmSearchConditionDTO alarmSearchConditionDTO) {

    AlarmSearchResponseDTO alarmSearchResponseDTO = new AlarmSearchResponseDTO();

    List<AlarmSearchDAO> searchList = null;
    log.info("{}", alarmSearchConditionDTO);

    
    try {
        searchList = (List<AlarmSearchDAO>) alarmRecordMapper.selectAlarmInfo(alarmSearchConditionDTO);
    } catch (NullPointerException e) {
        // 조회건수 0 -> 빈리스트 리턴
    }
    int totalCnt = alarmRecordMapper.countAlarmInfo(alarmSearchConditionDTO);

    Pagination paging = new Pagination();
    paging.setPageNum(alarmSearchConditionDTO.getPageNum());
    paging.setPageSize(alarmSearchConditionDTO.getPageSize());
    paging.setOrderColumn(alarmSearchConditionDTO.getSortColumn());
    paging.setOrderType(alarmSearchConditionDTO.getSortType());
    paging.setTotalCnt(totalCnt);
    paging.setTotalPageCnt(alarmSearchConditionDTO.setTotalPageNum(totalCnt));

    alarmSearchResponseDTO.setPagination(paging);
    alarmSearchResponseDTO.setResult(searchList);


    return alarmSearchResponseDTO;
}

제가 myBatis 사용을 위해 검색 조건 DTO안에 requestPaging이란 페이징 을 위한 객체를 만들어서 사용을 하고 싶습니다.

컨트롤러에서 get호출을 받으면 받고 난 뒤 빌더를 이용하여 DTO에 세팅을 하면 아래의 데이터가 나옵니다.

AlarmSearchConditionDTO(siteName=null, startTime=null, endTime=null, cameraName=Camera A, accidentType=null, modelVersion=null, action=null, sortColumn=eventTime, sortType=null,

paging=requestPaging(pageNum=7, pageSize=3, totalPageCnt=0))

 여기까지는 페이징 처리를 위한 변수들이 정상적으로 들어갔습니다.

mapper에서 parameterType="AlarmSearchConditionDTO" 로 사용하여 검색 조건과 페이징 처리를 모두 하려고 합니다. mapper에서 #{startPage} 과 같은 타입은parameterType.get~() 메서드를 사용하여 뽑는 것으로 알고 있습니다.

하지만 그 후 데이터베이스 조회 페이징 처리를 위해 아래의 두가지 변수를 이용하여 mapper에서 처리를 하려하는데

alarmSearchConditionDTO.getStartPage()
alarmSearchConditionDTO.getPageSize()

DTO 자체를 로그 찍어서 확인을 하면 pageNum과 pageSize 가 받아온 값으로 잘 저장이 되는데,

DTO.get() 변수를 사용해서 값을 확인하면 requestPaging 클래스의 생성자의 디폴트 값이 호출되어 1과 30이 나옵니다.

public requestPaging() {
    this.pageNum = 1;
    this.pageSize = 30;
}

 

계속 고민하다가 모르겠어서 질문드립니다.. 도와주세요 ㅠㅠ

 

 

 

 

 

답변 1

0

인프런 AI 인턴님의 프로필 이미지

2023. 09. 14. 19:01

안녕하세요, 인프런 AI 인턴이에요. 자바 코드에 대한 질문이신 것 같아요. 어떤 내용을 도와드릴까요?

주어진 코드는 AlarmSearchResponseDTO 객체를 반환하는 alarmList 메서드를 정의한 것 같습니다. 이 메서드는 @GetMapping 어노테이션을 사용하여 “/alarm” 경로로 GET 요청을 처리합니다. 메서드의 매개변수로는 다양한 Query Parameter 값을 받아옵니다.

코드 상에서 필요한 Query Parameter 값을 받아와 AlarmSearchConditionDTO 객체를 생성하고, 이 객체에 값들을 세팅하는 것을 볼 수 있습니다. 이렇게 생성된 AlarmSearchConditionDTO 객체는 해당 메서드 내에서 사용되는 것으로 보입니다.

자세한 내용이 있으시면 댓글로 알려주세요. 도움이 될 수 있도록 최대한 도와드리겠습니다.

nhkwak71님의 프로필 이미지

작성한 질문수

질문하기