Springboot hibernate

网友投稿 297 2022-09-07


Springboot hibernate

目录一、版本信息及maven依赖二、定义实体bean三、测试Controller四、hibernate-validator全局异常处理五、hibernate-validator快速校验

一、版本信息及maven依赖

hibernate-validator 7.x版本有问题,暂时以6.2.1.Final为例,6.2.1.Final版本解决了Log4j版本的漏洞

1.8

UTF-8

UTF-8

5.7.16

6.2.1.Final

记得引入:spring-boot-starter-validation

org.springframework.boot

spring-boot-starter-validation

org.hibernate.validator

hibernate-validator

cn.hutool

hutool-all

${hutool.version}

二、定义实体bean

import javax.validation.constraints.Email;

import javax.validation.constraints.Max;

import javax.validation.constraints.Min;

import javax.validation.constraints.NotBlank;

import org.hibernate.validator.constraints.Length;

public class User {

private Integer id;

@Min(18)

@Max(200)

private Integer age;

@NotBlank(message = "姓名不能为空")

@Length(min = 2, max = 6, message = "长度必须在{min}和{max}个字符之间")

private String name;

@NotBlank(message = "电子邮箱不能为空")

@Email(message = "电子邮箱格式不正确")

private String email;

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public Integer getAge() {

return age;

}

public void setAge(Integer age) {

this.age = age;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getEmail() {

return email;

}

public void setEmail(String email) {

this.email = email;

}

@Override

public String toString() {

return "User [id=" + id + ", age=" + age + ", name=" + name + ", email=" + email + "]";

}

}

三、测试Controller

需要在类上面加上注解:@Validated

import javax.validation.Valid;

import javax.validation.constraints.NotNull;

import org.springframework.validation.annotation.Validated;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

@RestController

@Validated

public class UserController {

@RequestMapping("/get")

public User get(@NotNull(message = "id不能为空") Integer id,

@NotNull(message = "姓名不能为空") String name) {

User user = new User();

user.setName("lisi");

user.setId(id);

return user;

}

@RequestMapping("/save")

public User get(@Valid User user) {

return user;

}

}

四、hibernate-validator全局异常处理

import java.util.List;

import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.validation.ConstraintViolation;

import javax.validation.ConstraintViolationException;

import org.springframework.http.HttpStatus;

import org.springframework.validation.BindException;

import org.springframework.validation.FieldError;

import org.springframework.web.bind.MethodArgumentNotValidException;

import org.springframework.web.bind.annotation.ControllerAdvice;

import org.springframework.web.bind.annotation.ExceptionHandler;

import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice

public class GlobalException {

public static final String DELIM = ",";

@ExceptionHandler(Exception.class)

@ResponseBody

public String exceptionHandler(HttpServletRequest request, HttpServletResponse response,

Exception e) {

if(e instanceof ConstraintViolationException) {

//@RequestParam上参数validate失败后抛出的异常

ConstraintViolationException cve = (ConstraintViolationException) e;

Set> violations = cve.getConstraintViolations();

StringBuffer sb = new StringBuffer("");

for (ConstraintViolation> constraintViolation : violations) {

sb.append(constraintViolation.getMessage()).append(DELIM);

}

if(sb.indexOf(DELIM) > -1) {

sb.deleteCharAt(sb.length() - 1);

}

System.out.println("ConstraintViolationException sb="+sb);

response.setStatus(HttpStatus.BAD_REQUEST.value());

return sb.toString();

}else if(e instanceof BindException) {

//@RequestParam上实体对象validate失败后抛出的异常

BindException be = (BindException) e;

System.out.println("be.getMessage()="+be.getMessage());

List fieldErrors = be.getBindingResult().getFieldErrors();

StringBuffer sb = new StringBuffer("");

for (FieldError fieldError : fieldErrors) {

sb.append(fieldError.getDefaultMessage()).append(DELIM);

//System.out.println("fieldError.getDefaultMessage() =" + fieldError.getDefaultMessage());

}

if(sb.indexOf(DELIM) > -1) {

sb.deleteCharAt(sb.length() - 1);

}

System.out.println("BindException sb="+sb);

response.setStatus(HttpStatus.BAD_REQUEST.value());

return sb.toString();

}else if(e instanceof MethodArgumentNotValidException) {

//@RequestBody上validate失败后抛出的异常

MethodArgumentNotValidException mave = (MethodArgumentNotValidException) e;

System.out.println("mave.getMessage() = " + mave.getMessage());

List fieldErrors = mave.getBindingResult().getFieldErrors();

StringBuffer sb = new StringBuffjsGcPeklGer("");

for (FieldError fieldError : fieldErrors) {

sb.append(fieldError.getDefaultMessage()).append(DELIM);

//System.out.println("fieldError.getDefaultMessage() =" + fieldError.getDefaultMessage());

}

if(sb.indexOf(DELIM) > -1) {

sb.deleteCharAt(sb.length() - 1);

}

System.out.println("MethodArgumentNotValidException sb="+sb);

response.setStatus(HttpStatus.BAD_REQUEST.value());

return sb.toString();

}

return "系统异常";

}

}

五、hibernate-validator快速校验

hibernate-validator默认会全部校验后再返回所有错误结果,为了让hibernate-validator检查到第一个错误马上返回结果,需要配置快速校验

import javax.validation.Validation;

import javax.validation.Validator;

import javax.validation.ValidatorFactory;

import org.hibernate.validator.HibernateValidator;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;

@Configuration

public class ValidatorConfiguration {

/**

* 快速返回校验器

* @return

*/

@Bean

@ConditionalOnMissingBean(value = Validator.class)

public Validator validator() {

//hibernate-validator 6.x没问题,7.x有问题

ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)

.configure()

.failFast(true)

//.addProperty("hibernate.validator.fail_fast", "true")

.buildValidatorFactory();

return validatorFactory.getValidator();

}

/**

* 设置快速校验,返回方法校验处理器

* @return

*/

@Bean

@ConditionalOnMissingBean(value = MethodValidationPostProcessor.class)

public MethodValidationPostProcessor methodValidationPostProcessor() {

MethodValidationPostProcessor postProcessor = new MethodValidationPostProcessor();

postProcessor.setValidator(validator());

return postProcessor;

}

}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:干货:Python中常见的数据结构和同数据有关的算法(python中常用的数据结构)
下一篇:Python神经网络:训练简单的分类器篇
相关文章

 发表评论

暂时没有评论,来抢沙发吧~