0

Lets say I create a validator for NewUserRequestBean called @CheckUsernameAvailable.

The validator would perform something simple like

public boolean isValid(NewUserRequestBean request, ConstraintValidationContext context) {
    String userName = request.getUserName();
    User existingUser = userProviderService.getUser(userName);
    if (existingUser != null) {
        return false;
    }
}

Is there a way to reuse the existingUser object, so as to do something like

// if (existingUser != null)
else if (existingUser.getEmailAddress() == request.getUserEmailAddress()) {
    sendObjectToCaller(existingUser);
    // or returnObjectToCaller(existingUser);
}
Lordbalmon
  • 1,634
  • 1
  • 14
  • 31

1 Answers1

0

In case you are using Hibernate Validator you can take a look at dynamic payload. Your implementation of validator would look like:

    @Override
    public boolean isValid(NewUserRequestBean value, ConstraintValidatorContext context) {
        // all the code you need

        // make sure that you are working with Hibernate Validator contexts before unwrapping
        if ( context instanceof HibernateConstraintValidatorContext ) {
            context.unwrap( HibernateConstraintValidatorContext.class )
                    .withDynamicPayload( existingUser );
        }

        return validationResult;
    }

and then you should be able to access this same payload from the constraint violation if one is raised:

    Set<ConstraintViolation<NewUserRequestBean>> violations = // results of validation of your NewUserRequestBean... 

    // just get the violation and unwrap it to HibernateConstraintViolation.
    // to stay on the safe side you should apply an instanceof check here as well before unwrapping
    HibernateConstraintViolation<NewUserRequestBean> violation = violations.iterator().next()
            .unwrap( HibernateConstraintViolation.class );

    User existingUser = violation.getDynamicPayload( User.class );

For more info you can check the javadocs of these dynamic payload methods and also please have a look at this section in documentation on dynamic payloads

mark_o
  • 2,052
  • 1
  • 12
  • 18