How to tell hibernate validator to validate only one annotation?

Martin Čuka :

Is it possible to tell hibernate validation to validate only one particular annotation ?
I've created custom annotation which use javax.validation.ConstraintValidator so far so good.
However when I want to manually validate Object using

javax.validation.Validator.validate(myOjbect);

it will validate all annotations including @NotNull, @Size... Is there an elegant way to override this behaviour so I can choose which annotations to validate ?

Selaron :

I can't find a way to limit validation to a particular annotation without modifying the validated class. You can limit it to a property by calling Validator##validateProperty(object, propertyName, ...) but the equivalent to explicitly limit it to a set of annotations requires to assign groups to annotations:

What seemes to work is this:

  1. Create an interface for each group of annotations you want to validate.
  2. Specify that interface for groups property of each annotation to validate with this group. If the annotation also must be validated by default, add the Default interface either.
  3. Add the interface to validator invocations.

An example:

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.validation.groups.Default;

public class SomeTest {

    public static void main(String[] args) {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();

        Cat a = new Cat(null);
        // invalid: name is null
        output(validator.validate(a), a);

        Cat b = new Cat("?");
        // invalid: name too short
        output(validator.validate(b), b);

        // valid: only @NotNull is evaluated, @Size does not matter.
        output(validator.validate(b, NotNullName.class), b);

        // invalid: only @NotNull is evaluated, @Size does not matter. Name is null.
        output(validator.validate(a, NotNullName.class), a);
    }

    /**
     * Output validation result.
     *
     * @param validate
     *            the validate
     */
    private static void output(Set<ConstraintViolation<Cat>> validationResult, Cat cat) {
        if (validationResult.isEmpty()) {
            System.out.println(cat + " is valid!");
        } else {
            System.out.println(cat + " is invalid!\n" + validationResult);
        }
    }

    // no need to implement an interface - just name it for annotation groups attribute:
    public static class Cat {
        @NotNull(groups = { NotNullName.class, Default.class })
        @Size(min = 3, max = 45)
        private String name;

        public Cat(String name) {
            super();
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            StringBuilder builder = new StringBuilder();
            builder.append("Cat [");
            if (name != null) {
                builder.append("name=");
                builder.append(name);
            }
            builder.append("]");
            return builder.toString();
        }

    }

    public static interface NotNullName {
        // no members needed here
    }
}

Output:

Cat [] is invalid!
[ConstraintViolationImpl{interpolatedMessage='darf nicht null sein', propertyPath=name, rootBeanClass=class SomeTest$Cat, messageTemplate='{javax.validation.constraints.NotNull.message}'}, ConstraintViolationImpl{interpolatedMessage='darf nicht null sein', propertyPath=name, rootBeanClass=class SomeTest$Cat, messageTemplate='{javax.validation.constraints.NotNull.message}'}]
Cat [name=?] is invalid!
[ConstraintViolationImpl{interpolatedMessage='Länge muss zwischen 3 und 45 liegen', propertyPath=name, rootBeanClass=class SomeTest$Cat, messageTemplate='{javax.validation.constraints.Size.message}'}]
Cat [name=?] is valid!
Cat [] is invalid!
[ConstraintViolationImpl{interpolatedMessage='darf nicht null sein', propertyPath=name, rootBeanClass=class SomeTest$Cat, messageTemplate='{javax.validation.constraints.NotNull.message}'}]

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

How to tell Hibernate to use a proxy?

分類Dev

2 nics each with static IP addresses - how to tell only one to accept inbound

分類Dev

Does java web application contains only one hibernate session and how to clear this hibernate session?

分類Dev

Express-validator: How can we validate an Object keys?

分類Dev

Node.js: How to handle multiple validate with validator.js

分類Dev

Hibernate annotation mapping for One-To-Many bidirectional relation with DerbyDB

分類Dev

How to validate a Jtextfield to only allow letters in Java?

分類Dev

how to validate field to contain only specific values?

分類Dev

Java Repeatable annotation not recognized when it's only one parameter

分類Dev

Java Repeatable annotation not recognized when it's only one parameter

分類Dev

How can I validate distinct pairs of fields in a List in MVC with a custom remote validator?

分類Dev

How nested FETCH JOIN works on Hibernate using JpaRepository and @Query annotation?

分類Dev

How do I tell the `date` command to only show the time?

分類Dev

Update an entity with Hibernate whose only one field is editable in DB

分類Dev

Laravel 5.6 $ this-> validate vs Validator :: make()

分類Dev

How to create javax.el.ExpressionFactory in Google App Engine to use Hibernate Validator

分類Dev

How to trigger only one entry?

分類Dev

How to allow to only one dot?

分類Dev

How to validate a letter and whitespace only input via JavaScript regular expression

分類Dev

How to define an annotation for more than one target in Groovy?

分類Dev

Validate ending letters only

分類Dev

Java Bean Validation 2.0とHibernate Validator

分類Dev

Hibernate Validator 検証セット

分類Dev

Text Adventure Game - How to Tell One Item Type from Another and How to Structure the Item Classes/Subclasses?

分類Dev

How to tell TypeScript to allow multiple strings from a list, each, only once in a spread parameter?

分類Dev

How to apply plugin to only one flavor in gradle?

分類Dev

Android - Crashlytics - How to upload only one app

分類Dev

How to run only one timer in web

分類Dev

How to deselect only one particular item in a slicer

Related 関連記事

  1. 1

    How to tell Hibernate to use a proxy?

  2. 2

    2 nics each with static IP addresses - how to tell only one to accept inbound

  3. 3

    Does java web application contains only one hibernate session and how to clear this hibernate session?

  4. 4

    Express-validator: How can we validate an Object keys?

  5. 5

    Node.js: How to handle multiple validate with validator.js

  6. 6

    Hibernate annotation mapping for One-To-Many bidirectional relation with DerbyDB

  7. 7

    How to validate a Jtextfield to only allow letters in Java?

  8. 8

    how to validate field to contain only specific values?

  9. 9

    Java Repeatable annotation not recognized when it's only one parameter

  10. 10

    Java Repeatable annotation not recognized when it's only one parameter

  11. 11

    How can I validate distinct pairs of fields in a List in MVC with a custom remote validator?

  12. 12

    How nested FETCH JOIN works on Hibernate using JpaRepository and @Query annotation?

  13. 13

    How do I tell the `date` command to only show the time?

  14. 14

    Update an entity with Hibernate whose only one field is editable in DB

  15. 15

    Laravel 5.6 $ this-> validate vs Validator :: make()

  16. 16

    How to create javax.el.ExpressionFactory in Google App Engine to use Hibernate Validator

  17. 17

    How to trigger only one entry?

  18. 18

    How to allow to only one dot?

  19. 19

    How to validate a letter and whitespace only input via JavaScript regular expression

  20. 20

    How to define an annotation for more than one target in Groovy?

  21. 21

    Validate ending letters only

  22. 22

    Java Bean Validation 2.0とHibernate Validator

  23. 23

    Hibernate Validator 検証セット

  24. 24

    Text Adventure Game - How to Tell One Item Type from Another and How to Structure the Item Classes/Subclasses?

  25. 25

    How to tell TypeScript to allow multiple strings from a list, each, only once in a spread parameter?

  26. 26

    How to apply plugin to only one flavor in gradle?

  27. 27

    Android - Crashlytics - How to upload only one app

  28. 28

    How to run only one timer in web

  29. 29

    How to deselect only one particular item in a slicer

ホットタグ

アーカイブ