Hibernate 提供了内置的验证框架,可以对实体类的属性值进行校验。以下是使用 Hibernate 进行数据校验的步骤:
@NotEmpty
、@NotNull
、@Size
、@Pattern
等,以定义属性值的校验规则。import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotEmpty(message = "用户名不能为空")
@Size(min = 3, max = 20, message = "用户名长度必须在3到20个字符之间")
private String username;
@NotEmpty(message = "密码不能为空")
@Size(min = 6, max = 20, message = "密码长度必须在6到20个字符之间")
private String password;
// getter 和 setter 方法
}
pom.xml
文件中添加以下依赖:<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>7.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>3.0.0</version>
</dependency>
Validator
对象对实体类的属性值进行校验。如果校验失败,可以抛出自定义的异常或返回错误信息。import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;
public class UserService {
private final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
public void createUser(User user) {
Set<ConstraintViolation<User>> violations = validator.validate(user);
if (!violations.isEmpty()) {
StringBuilder sb = new StringBuilder();
for (ConstraintViolation<User> violation : violations) {
sb.append(violation.getMessage()).append("; ");
}
throw new IllegalArgumentException("参数校验失败: " + sb.toString());
}
// 保存用户或执行其他操作
}
}
IllegalArgumentException
异常,返回相应的错误信息给客户端。import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<String> handleIllegalArgumentException(IllegalArgumentException e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
}
通过以上步骤,可以使用 Hibernate 对实体类的属性值进行校验,并在校验失败时返回相应的错误信息。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。