java - Spring Boot 未验证实体上的嵌入式对象
问题描述
我正在尝试向我的 REST API 发送 POST 请求。名称、描述等所有字段...根据需要工作并使用 @NotNull 等验证器正确验证。但是,当涉及到嵌入对象时,没有任何字段正在验证。当没有任何位置字段被传递时,它不会显示错误,只是将它们默认为 0
我已经尝试过使用前面帖子中提到的@Valid 注释,但这似乎仍然没有奏效。
实体
@Entity
@Table(name = "loos")
public class Loo implements Serializable {
private static final long serialVersionUID = 9098776609946109227L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name = "uuid", columnDefinition = "BINARY(16)")
private UUID uuid;
@NotNull(message = "Name cannot be null")
@Column(name = "name")
private String name;
@NotNull(message = "Description cannot be null")
@Type(type="text")
@Column(name = "description")
private String description;
@NotNull(message = "Location cannot be null")
@Embedded
@AttributeOverrides({ @AttributeOverride(name = "lat", column = @Column(name = "location_lat")),
@AttributeOverride(name = "lng", column = @Column(name = "location_lng")) })
@Valid
private LatLng location;
培训班
@Embeddable
public class LatLng {
@NotNull(message = "Lat cannot be null")
private double lat;
@NotNull(message = "Lat cannot be null")
private double lng;
protected LatLng() {
}
public double getLat() {
return this.lat;
}
public double getLng() {
return this.lng;
}
}
我本来希望 LatLng 类内部的错误消息会说“LatLng - lat is required”或类似的东西。相反,操作将继续,只是将它们的值默认为 0
解决方案
对于原始数据类型,它将具有默认值。在您的情况下,double 将具有默认值 0.0d。所以当使用 NotNull 检查该值是否有效时,它将是有效的。
您可以将原始数据类型更改为其 Wrapper 类,如下所示。(双至双)
@NotNull(message = "Lat cannot be null")
private Double lat;
@NotNull(message = "Lat cannot be null")
private Double lng;
推荐阅读
- jquery - 在 Rails 5 中使用 jquery 自动完成多个字段
- android - 每当进入特定活动屏幕时,应用程序会因 Pending Intent 而崩溃
- java - 无法打开玛丽模拟器
- mysql - mysql slave db错误连接到master
- python - Python/Pandas 通过一个限制获得所有可能的组合
- linux - 在子目录中获取最新的文件(同名)
- c++ - C++ 运算符优先级查询
- inno-setup - 在 Inno Setup 的自定义页面上显示控件背后的背景
- c# - 当我想使用我的搜索功能时,数据未从 UWP 中的 SQL Server 数据库中显示,带有 gridview 和错误
- c++ - reinterpret_cast 错误还是 UB?