I m trying to develop a Spring boot with MongoDB and my problem is that I don't want that a user to put in the DB empty or null
value for some field.
I already tried the option that I found on the web but it didn't work.
Code:
@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;
}
CodePudding user response:
You are using
@NotNull
Which is used for validation a model.
For omitting storing null
values to DB you should use:
@Column(nullable=false)
private String brand;
UPDATE:
Looks like your schema has been already generated.
You didn't share the DB configuration of your project.
If you are using Spring Boot, you have to set at application.properties
additional properties to make it work:
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.check_nullability=true
However, it will help do not store null
values.
For preventing to store empty values you should add for string fields:
@Size(min=1)
If you want to validate Integer or Double that they have values more than 0
, use @Min
:
@Min(value = 1L, message = "The price must be positive")
private Double price;