June222 / Smart-Factory-Project

0 stars 1 forks source link

javaNullPointException #27

Closed June222 closed 8 months ago

June222 commented 8 months ago

서버를 시작하는데 Error가 뜸

Response Body

{
    "timestamp": "2023-10-21T16:17:45.515+00:00",
    "status": 500,
    "error": "Internal Server Error",
    "trace": "java.lang.NullPointerException\r\n\tat com.example.demo1.domain.Steel.addLabel(Steel.java:61)\r\n\tat com.example.demo1.dto.SteelReqDto$AddReqDto.toEntity(SteelReqDto.java:41)\r\n\tat com.example.demo1.service.SteelService.addData(SteelService.java:26)\r\n\tat com.example.demo1.service.SteelService$$FastCla
...
}

Log

toEntity Process
Steel(id=null, fileName=123, originImgUrl=originURL, detectedImgUrl=detectedImgURL, isNormal=false, labels=null, localDateTime=null)
label:1
com.example.demo1.domain.SteelLabel@e84a82ff
2023-10-22 01:17:45.504 ERROR 23108 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause

java.lang.NullPointerException: null
    at com.example.demo1.domain.Steel.addLabel(Steel.java:61) ~[main/:na]
    at com.example.demo1.dto.SteelReqDto$AddReqDto.toEntity(SteelReqDto.java:41) ~[main/:na]
    at com.example.demo1.service.SteelService.addData(SteelService.java:26) ~[main/:na]
    ... 후략

SteelService.addData() Code

    @Transactional
    public AddRespDto addData(AddReqDto requestDTO){
        Steel steelPS = steelRepository.save(requestDTO.toEntity());
        return new AddRespDto(steelPS);
    }

AddReqDto.toEntity() Code

public Steel toEntity(){
            System.out.println("toEntity Process");
            Steel steel = Steel.builder()
                    .fileName(fileName)
                    .originImgUrl(originImgUrl)
                    .detectedImgUrl(detectedImgUrl)
//                    .labels(new ArrayList<>())
                    .build();

            System.out.println(steel);
            for (Integer label: defectLabelList){
                System.out.println("label:" + label);
                SteelLabel steelLabel = SteelLabel.createLSteelLabel(label, steel);
                System.out.println(steelLabel);
                steel.addLabel(steelLabel);
                System.out.println(steel);
            }
            System.out.println("toEntity done.");
            return steel;
        }

addLabel() Code


    public void addLabel(SteelLabel label){
        this.labels.add(label);
    }
June222 commented 8 months ago
@Entity
class Steel {
...
    @OneToMany(mappedBy = "steel", orphanRemoval = true, cascade = CascadeType.ALL)
    private List<SteelLabel> labels = new ArrayList<SteelLabel>();
...
}

해결: List의 부재

Steel Instance 생성 시에 builder()를 통해서 생성하는 경우 기본 선언에 빈 ArrayList<>()가 있음에도 적용받지 않음.

따라서 위 toEntity()코드에 주석 부분을 해제하여 해결할 수 있음.