【问题标题】:JPA - How to make field not required in JSON POST requestJPA - 如何使 JSON POST 请求中不需要的字段
【发布时间】:2019-09-15 23:14:13
【问题描述】:

我不想在 JSON POST 请求中传递价格字段,而是通过 setPrice() 自定义方法计算。

当我在 JSON POST 请求中传递我不想传递的价格字段时,无论值如何,它都可以正常工作,并且我的字段被正确计算并存储在 MySQL 表中。当我不通过它时,它只是出于某种原因返回并存储 0。

@Entity
public class User {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int user_id;

private String name;

@JsonFormat(pattern = "dd/MM/yyyy", timezone = "Europe/Berlin")
private Date date1;

@JsonFormat(pattern = "dd/MM/yyyy", timezone = "Europe/Berlin")
private Date date2;

private int beds;

private int meals;

private double price;


public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getUser_id() {
    return user_id;
}

public void setUser_id(int user_id) {
    this.user_id = user_id;
}

public double getPrice() {
    return price;
}


public void setPrice(double price) {

    this.price = (double) computePrice(date1, date2, beds, meals);
}

public int getBeds() {
    return beds;
}

public void setBeds(int beds) {
    this.beds = beds;
}

public Date getDate1() {
    return date1;
}

public void setDate1(Date date1) {
    this.date1 = date1;
}

public int getMeals() {
    return meals;
}

public void setMeals(int meals) {
    this.meals = meals;
}

public Date getDate2() {

    return date2;
}

public void setDate2(Date date2) {
    this.date2 = date2;
}


public long computePrice(Date date1, Date date2, int beds, int meals) {

    long duration = date2.getTime() - date1.getTime();

    long diffInDays = TimeUnit.MILLISECONDS.toDays(duration);

    if (diffInDays < 0) {
        return 0;
    }

    double priceBeds;
    double priceMeals = 700;

    if (beds == 1) {
        priceBeds = 2200;
    } else if (beds == 2) {
        priceBeds = 3300;
    } else if (beds == 3) {
        priceBeds = 4100;
    } else {
        priceBeds = 0;
    }

    if (meals < 0 || meals > 3) {
        meals = 0;
    }

    return (long) (diffInDays * (priceBeds + (meals * priceMeals)));

}

【问题讨论】:

  • 您的用例正好超过了实体加倍为 DTO 的方法打破的细线

标签: mysql spring hibernate spring-boot jpa


【解决方案1】:

您正在为价格字段使用double 原语。 double 原语的默认值为 0,所以当不传递时,它被初始化为它。

如果你将使用Double 对象,则未传递时的默认值为空

【讨论】:

  • 现在它只返回空值。有没有办法根本不传递价格字段值?我希望它由 setPrice() 方法计算,而不是由用户传递。
  • 这取决于你如何序列化你对 json 的响应,但是你应该使用忽略空值的 sierallizer
猜你喜欢
  • 2017-02-19
  • 2020-11-25
  • 2021-01-03
  • 2019-07-12
  • 2020-07-20
  • 2021-02-07
  • 2018-07-12
  • 1970-01-01
  • 2023-01-20
相关资源
最近更新 更多