Home > Software engineering >  How to solve int value to null in RESTful API update situation?
How to solve int value to null in RESTful API update situation?

Time:09-21

Sorry for bad english.

I currently use dto for request body mapping,

Spring can not know input is null or not received, because both situation is just null.

As an example, Like this.


// dto
public class UpdateDto {
  private String name;
  private Integer price;
}

// entity
public class Product {
  @Id
  @GeneratedValue
  private Long id;

  @Column(nullable = true)
  private String name;

  @Column(nullable = true)
  private Integer price;
}

I solved in string case using empty string. When empty string received, update this field to null. Because most of case empty string can treated as null.


// update name
if (updateDto.getName() != null) {
  if (updateDto.getName() == "") {
    // set name to null
  } else {
    // just update to getName() value
  }
}

// update price
// when i set to null?

However integer case, I don't know how can i solve this problem. Anything good idea?

CodePudding user response:

you can use primitive data type int and set nullable as false since null doesn't make sense for numbers

use primitive data type for price in both entity and dto Entity:

  @Column(nullable = false)
  private int price;

DTO:

 private int price;

CodePudding user response:

I found the easiest solution.

related link(In korean): https://www.it-gundan.com/ko/java/spring-rest-controller에서-부분-업데이트에-대해-null-값과-제공되지-않은-값을-구별하는-방법/827265839/

the solution is, add dirty check boolean flag in setter. in case of above,

// dto
public class UpdateDto {
  private String name;
  private Integer price;
  private Boolean isPriceDirty;

  // when setter setPrice,
  public void setPrice(Integer price) {
    this.price = price;
    this.isPriceDirty = true;
  }
}

then, output can set null only when dirty is true.

  • Related