我正在嘗試使用 MongoDB 開發 Spring Boot,但我的問題是我不希望用戶將資料庫中的內容為空或null某些欄位的值。
我已經嘗試了我在網上找到的選項,但它不起作用。
代碼:
@Data
@Entity
@Document(collection = "product")
public class Product {
@Id
private String id;
@NotEmpty
private String name;
@NotNull(message = "brand must not be null")
private String brand;
@NotNull(message = "barCode must not be null")
private String barCode;
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
private LocalDate importDate;
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
private LocalDate expireDate;
@NotNull(message = "price must not be null")
private Double price;
private Double deal;
@NotNull(message = "the quantity must not be null")
private Integer quantity;
}
uj5u.com熱心網友回復:
您正在使用
@NotNull
用于驗證模型。
要省略將null值存盤到DB,您應該使用:
@Column(nullable=false)
private String brand;
更新:
看起來您的架構已經生成。
您沒有共享專案的資料庫配置。
如果您使用的是 Spring Boot,則必須設定application.properties其他屬性才能使其作業:
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.check_nullability=true
但是,它有助于不存盤null值。
為了防止存盤空值,您應該為字串欄位添加:
@Size(min=1)
如果要驗證Integer或Double的值是否大于0,請使用@Min:
@Min(value = 1L, message = "The price must be positive")
private Double price;
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/430157.html
