【发布时间】: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