javax validation does not validate notNull

Viewed 2599

I have a springBoot 2.1.9.RELEASE application that uses Spring Data for Couchbase

I have this object

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Hostel<T> {

    @NotNull
    @JsonProperty("_location")
    private T location;

}

and this other one

@Document
@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(of = { "id" })
@Builder
public class HTMDoc {

    @Id
    private String id;
    @NotNull
    @Field
    private Hostel hostel;

}

on the service

public HTMDoc create(@Valid HTMDoc doc) {
    return repository.save(doc);
}

on the test

service.create(new HTMDoc());

but when I save I got this error instead of the validation NotNull in the hostel field

 org.springframework.data.mapping.MappingException: An ID property is needed, but not found/could not be generated on this entity.
6 Answers

You need to use the @org.springframework.validation.annotation.Validated annotation over your service class to enable validation.

@Validated
@Service
public class DocService {
  public HTMDoc create(@Valid HTMDoc doc) {
    return repository.save(doc);
  }
}

Add the following annotation to the id and give it a try:

@Id
@GeneratedValue(strategy = GenerationStrategy.UNIQUE)
private String id;

More info about @GeneratedValue annotation can be found in this great answer: Spring GeneratedValue annotation usage

Put the annotation on the getter.

Maybe the validation is not supported in private fields.

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Hostel<T> {
    @Id
    private Long id;
    @NotNull
    @JsonProperty("_location")
    private T location;

}

Using @Id on any property is mandatory in Model classes.

please add the following syntax on your id field

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Hostel<T> {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false, updatable = false)
    private Long id;

    @NotNull
    @JsonProperty("_location")
    private T location;

}

also use the validate annotation in your service class.

@Validated
@Service
public class DocService {
  public HTMDoc create(@Valid HTMDoc doc) {
    return repository.save(doc);
  }
}

You need to use the @Validated annotation in your classes to inform the spring boot that these classes are should be validated by javax validations.

@Validated
@Component
public class Phone {
 //Your logic
}
Related