【问题标题】:Can I avoid to add in mongoDB null value for some field?我可以避免为某些字段添加 mongoDB 空值吗?
【发布时间】:2022-02-07 10:18:35
【问题描述】:

我正在尝试使用 MongoDB 开发 Spring Boot,但我的问题是我不希望用户为某些字段输入 DB emptynull 值。

我已经尝试了我在网上找到的选项,但它不起作用。

代码:

@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;
}

【问题讨论】:

  • 当字段值为空或为空时,可能有一个默认值。它是一个什么样的领域?您在寻找验证 - 在哪里?在数据库服务器,还是应用服务器级别?如果您不希望用户输入空值或空值,也许可以在客户端验证时注意。
  • 我知道我可以在视图中放更多的行,但是我不想使用很多 if 语句,它不能像 sql 一样

标签: java spring mongodb spring-boot spring-mvc


【解决方案1】:

你正在使用

@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)

如果您想验证 IntegerDouble 的值是否大于 0,请使用 @Min

@Min(value = 1L, message = "The price must be positive")
private Double price;

【讨论】:

  • 它不起作用
  • @Robs 更新了答案
  • 它没有用,但我只是添加了更多 if 语句,所以用户必须添加,无论如何谢谢?
猜你喜欢
  • 2019-10-06
  • 2020-06-19
  • 1970-01-01
  • 2020-02-11
  • 1970-01-01
  • 1970-01-01
  • 2020-07-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多