Home > Blockchain >  Hwo can I convert from entity to dto with Null value in JPA
Hwo can I convert from entity to dto with Null value in JPA

Time:03-17

Here is my Service class.

public AnswerDetailResponse addAnswerByQuestionId(Long id, WriteAnswerRequest request) {

    Post post = request.toEntity();
    post.createAnswer(id);
    
    questionRepository.save(post);

    return AnswerDetailResponse.fromEntity(post);
}

and this is my fromEntity method of WriteAnswerRequest class

@ApiModel
@Data
@NoArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class AnswerDetailResponse {

    private long questionId;
    private long answerId;
    private String body;
    private int score;
    ...
}

public static AnswerDetailResponse fromEntity(Post entity) {
    AnswerDetailResponse response = new AnswerDetailResponse();

    response.setQuestionId(entity.getParentId());
    response.setAnswerId(entity.getId());
    response.setBody(entity.getBody());
    response.setScore(entity.getScore());
    response.setTags(entity.getTags());
    response.setAccepted(BaseUtil.isEqual(entity.getAcceptAnswerId(), entity.getId()));
    response.setLink(SysConfig.QUESTION_DEFAULT_URL   entity.getParentId());
    response.setCreatedAt(entity.getCreatedAt());
    response.setLastEditedAt(entity.getLastEditedAt());
    response.setUsed(entity.getIsUsed());
    response.setDeleted(entity.getIsDeleted());

    return response;
}

now, I don't get the 'score' value from request. So, I got the Exception. Without any library like mapstruct, modelmapper ... Is there any effective way to solve this problem..?

the Score can be got from request or not...

CodePudding user response:

Take a closer look in your Dto AnswerDetailResponse

private int score;

int is a primitive which can not hold null value.

Change this into

private Integer score;

CodePudding user response:

Since there is a possibility for this line entity.getScore() to produce Null, then to set the value of score regardless, what you can do is this:

response.setScore(Optional.ofNullable(entity.getScore()).orElse(0));

NB: Assume the data type for score is an integer for example

  • Related