很抱歉,我的英語不好。
我目前使用dto來實作請求體的映射,
Spring不能知道輸入是空還是沒有收到,因為兩種情況都是空的。
Spring不能知道輸入是空還是沒有收到,因為這兩種情況都是空的。
舉個例子,像這樣。
// 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;
我使用空字串解決了字串的問題。當收到空字串時,將這個欄位更新為空。因為在大多數情況下,空字串可以被視為空。
//更新名稱
if (updateDto.getName() != null) {
if (updateDto.getName() == ""/span>) {
//設定名稱為空。
} else {
//只是更新到getName()的值。
}
}
//更新價格。
//當我設定為null?
然而在整數情況下,我不知道如何解決這個問題。 有什么好主意嗎?
uj5u.com熱心網友回復:
你可以使用原始資料型別int,并設定nullable為false,因為null對數字沒有意義
在entity和dto中為price使用原始資料型別。
物體:
@Column(nullable = false)
private int price。
DTO:
private int price;
uj5u.com熱心網友回復:
我找到了最簡單的解決方案。
相關鏈接(在韓國)
解決方案是,在setter中添加dirty check boolean標志。 在上述情況下,
// dto。
public class UpdateDto {
private String name;
private Integer price;
private Boolean isPriceDirty;
//當setter setPrice時,
public void setPrice(Integer price) {
this.price = price;
this.isPriceDirty = true;
}
}
那么,只有當dirty為真時,輸出才能設定為空。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/324186.html
標籤:
