Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate an method argument with @Validated annotation based on group

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.javato 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 :

  1. Why @Validated does not trigger the javax's @NotNull ? Am I doing something wrong or does it not support it?
  2. Is there any any other way? cannot implement custom validator

NOTE : I am also using lombok if it has something to do with this.

like image 851
mayank vats Avatar asked Aug 05 '15 08:08

mayank vats


People also ask

What is the use of @validated annotation?

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

Is @valid and @validated the same?

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.

What is the use of @valid annotation in Spring?

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.


1 Answers

@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) { ... }

    ...
}
like image 166
rubensa Avatar answered Oct 02 '22 13:10

rubensa