Introduction and Use of Hibernate Validator

Posted by zak on Tue, 01 Oct 2019 05:12:34 +0200

Preface

Recently, when developing the function of a module, it contains a lot of steps of blanking and validating the request parameters, and there are a lot of repeated judgments. Validation affects the beauty of the code and then decides to optimize this part of the code. SpringBoot comes with its own parameter validation box, Hibernate Validator. Here are your own learning notes.

rely on

If you use SptingBoot, include this framework dependency in the spring-boot-starter-web package, and add dependencies to other frameworks.

    <dependency>
      <groupId>org.hibernate.validator</groupId>
      <artifactId>hibernate-validator</artifactId>
      <version>6.0.17.Final</version>
    </dependency>

Use

New Class User

package com.longhc.uublog;

import com.alibaba.fastjson.JSON;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import java.io.Serializable;

@Getter
@Setter
@NoArgsConstructor
public class User implements Serializable {
    private static final long serialVersionUID = -2164567260938543876L;

    private String userId;
    
    // Field userName cannot be null and length > 0
    @NotBlank
    private String userName;
    
    // Passwords need to match regular expressions
    @Pattern(regexp = "^[A-Z]{0,3}[0-9]{5,10}")
    private String password;

    // Verify that the e-mail format is correct
    @Email
    private String email;

    // Family address is not empty
    @NotNull
    private String address;

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }
}
  • Validator is used to verify that the incoming parameters conform to the rules
package com.longhc.uublog;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

@Slf4j
public class VaildatorTest {

    @Test
    public void test() {
        // Get the default Validator
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

        Consumer consumer = new Consumer();
        consumer.setUserName("longhaicheng");
        consumer.setAddress(null);
        consumer.setEmail("123456789");
        // Verify that the consumer meets the requirements and returns the set set set set. If the set set size() returns > 0, it indicates that there are irregular parameters, which are printed through the log.
        Set<ConstraintViolation<Consumer>> constraintViolations = validator.validate(consumer);
        if (constraintViolations.size() > 0) {
            for (ConstraintViolation<Consumer> constraintViolation : constraintViolations) {
                String message = constraintViolation.getMessage();
                log.error("message:{}", message);
            }
        }
    }
}
  • Log return:

  • Failure to validate parameters returns error messages, or you can customize error messages by configuring the message attribute in the annotations
@NotBlank(message = "field[userName]Not to be empty")
@Pattern(regexp = "^[A-Z]{0,3}[0-9]{5,10}",message = "field[password]Matching expression[{regexp}]")
@Email(message = "Error e-mail format")
@NotNull(message = "Family address is not empty")
  • To use this framework in Spring
package com.longhc.uublog;

import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.HibernateValidator;
import org.springframework.stereotype.Component;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;



@Component
@Slf4j
public class ValidatorUtil {

    public static Validator getValidator() {
        // Using Hibernate Validator
        Validator validator = Validation.byProvider(HibernateValidator.class)
                .configure()
                // Fast failures (i.e. the first parameter failure returns error messages instead of checking all parameters and returning all error messages at once)
                .failFast(true)
                .buildValidatorFactory()
                .getValidator();
        return validator;
    }

    /**
     * @param object object
     * @param groups groups
     */
    public void validateObject(Object object, Class<?>... groups) {
        Set<ConstraintViolation<Object>> constraintViolations = getValidator().validate(object, groups);
        if (constraintViolations.size() > 0) {
            for (ConstraintViolation<Object> constraintViolation : constraintViolations) {
                String message = constraintViolation.getMessage();
                log.error("errorMessage:{}", message);
            }
        }
    }
}

Topics: Java Hibernate Lombok Spring