I have an entity XYZ.java
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class XYZ extends BaseEntity implements Serializable {
@NotNull (groups = {Groups.Insert.class, Groups.Delete.class, Groups.Update.class, Groups.Select.class})
private String X;
and there is an interface XYZCRUD.java
to do CRUD operations on XYZ.java
@Validated
public interface XYZCRUD {
public int insert(@Valid XYZ entity) throws SomeException;
Although javax's @Valid works for @NotNull validation but it does not support passing validation group as annotation attribute from the method from where i am triggering the validation . So I tried using @Validated annotation which does allow to pass groups via an attribute "value" like this
@Validated
public interface XYZCRUD {
public int insert(@Validated(value=SomeGroup.class) XYZ entity) throws SomeException;
However it does not trigger the validation at all.I tried after removing the groups attribute from the field and also from the trigger annotation.
Conclusion : @Validated does not trigger @NotNull
Questions :
NOTE : I am also using lombok if it has something to do with this.
@Validated annotation is a class-level annotation that we can use to tell Spring to validate parameters that are passed into a method of the annotated class. @Valid annotation on method parameters and fields to tell Spring that we want a method parameter or field to be validated.
The @Valid annotation ensures the validation of the whole object. Importantly, it performs the validation of the whole object graph. However, this creates issues for scenarios needing only partial validation. On the other hand, we can use @Validated for group validation, including the above partial validation.
The @Valid annotation will tell spring to go and validate the data passed into the controller by checking to see that the integer numberBetweenOneAndTen is between 1 and 10 inclusive because of those min and max annotations.
@mayank-vats If you want to apply a group to specific method (not all public methods), you can use:
@Validated
public class MyClass {
@Validated({Group1.class})
public myMethod1(@Valid Foo foo) { ... }
@Validated({Group2.class})
public myMethod2(@Valid Foo foo) { ... }
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With