szibi
szibi

Reputation: 141

How to fix validation constraints in embedded object beeing ignored?

I have my entity object in Spring Boot & Hibernate REST API. This class has many fields. Part of them is embedded and validation constraints such as @Min @Max are not working on fields in @Embeddable class. Same validation rules work perfect in @Entity classes. I am using javax.validation.constraints.Max

My main object looks like this:

@Entity
public class Notice extends BaseEntity {

  @Embedded
  private MyEmbeddedClass myEmbeddedClass;

  @OneToOne(cascade = CascadeType.ALL)
  @JoinColumn(name = "entity_class_id")
  private MyEntityClass myEntityClass;

}   

And my @embedded class:

@Embeddable
public class MyEmbeddedClass {

  @Size(max = 50)
  private String label;

  @Max(100)
  private Integer percent;

}

@Max constraint on percent field is ignored, but @size is working perfectly

@Entity
public class MyEntityClass extends BaseEntity {

  @Size(max = 50)
  private String name;

  @Max(6000)
  private Integer size;

}

And here @Max constraint and @size constraint on fields size are beeeing created

Is there a way to fix this? My Spring boot version is 2.1.1 and I can create my database scripts manually but I'd like to avoid that and get almost perfect script thanks to hibernate

Upvotes: 5

Views: 2294

Answers (1)

veljkost
veljkost

Reputation: 1932

You need to add @Valid annotation on your embedded object if you want to validate the constraints defined in your @Embeddable object:

@Entity
public class Notice extends BaseEntity {

    @Embedded
    @Valid
    private MyEmbeddedClass myEmbeddedClass;

    ...
}

Upvotes: 12

Related Questions