Spring Boot not validating Embedded object on Entity

Connor Brady :

I'm trying to send a POST request to my REST API. All the fields such as name, description, etc... Work as needed and validate properly using the validators such as @NotNull. However, when it comes to the embedded object, non of the fields are validating. It will not show an error when none of the location fields are passed and just defaults them to 0

I've tried using the @Valid annotations as mentioned in previous posts, however this still seems to have not worked.

Entity

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

LatLng Class


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

}

I would have expected the error message for inside of the LatLng class to say "LatLng - lat is required" or something like this. Instead the operation will continue and just default them values to 0

vivekkurien :

For primitive datatypes, it will have default values. In your case double will have a default value 0.0d. So when checking whether the value is valid using NotNull, it will be valid.

You can change the primitive data types to their Wrapper class like below. (double to Double)

@NotNull(message = "Lat cannot be null")
private Double lat;

@NotNull(message = "Lat cannot be null")
private Double lng;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=126709&siteId=1