hibernate-validator

本文介绍如何在Maven项目中配置Hibernate Validator及其相关依赖,并详细解释了常用的约束注解,如@NotNull、@NotBlank等,同时提供了示例代码及验证方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

现更新地址: http://www.yiyehu.tech/archives/2019/05/23/hibernate-validator


在Maven project使用

Hibernate Validator Maven dependency

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

Maven dependencies for Unified EL reference implementation
如果没有提供EL表达式的实现,则在pom.xml中添加下面的依赖

<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.el</artifactId>
    <version>3.0.1-b09</version>
</dependency>

Hibernate Validator CDI portable extension Maven dependency
如果没有提供CDI(Contexts and Dependency Injection for Java,java的上下文和依赖注入),则在pom.xml中添加下面的依赖

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

###常用约束的注解

/**
 * Bean Validation 中内置的 constraint       
 * @Null   被注释的元素必须为 null       
 * @NotNull    被注释的元素必须不为 null       
 * @AssertTrue     被注释的元素必须为 true       
 * @AssertFalse    被注释的元素必须为 false       
 * @Min(value)     被注释的元素必须是一个数字,其值必须大于等于指定的最小值       
 * @Max(value)     被注释的元素必须是一个数字,其值必须小于等于指定的最大值       
 * @DecimalMin(value)  被注释的元素必须是一个数字,其值必须大于等于指定的最小值       
 * @DecimalMax(value)  被注释的元素必须是一个数字,其值必须小于等于指定的最大值       
 * @Size(max=, min=)   被注释的元素的大小必须在指定的范围内       
 * @Digits (integer, fraction)     被注释的元素必须是一个数字,其值必须在可接受的范围内       
 * @Past   被注释的元素必须是一个过去的日期       
 * @Future     被注释的元素必须是一个将来的日期       
 * @Pattern(regex=,flag=)  被注释的元素必须符合指定的正则表达式       
 * Hibernate Validator 附加的 constraint       
 * @NotBlank(message =)   验证字符串非null,且长度必须大于0       
 * @Email  被注释的元素必须是电子邮箱地址       
 * @Length(min=,max=)  被注释的字符串的大小必须在指定的范围内       
 * @NotEmpty   被注释的字符串的必须非空       
 * @Range(min=,max=,message=)  被注释的元素必须在合适的范围内 
 * @URL 被注释的元素必须是一个有效的URL
 */

#####1.限制参数不为空的区别
@NotEmpty
Asserts that the annotated string, collection, map or array is not null or empty.
被注释的string, collection, map or array不为 null 不为空

@NotBlank
Validate that the annotated string is not null or empty. The difference to NotEmpty is that trailing whitespaces are getting ignored.
用于字符串,相比较@NotEmpty而言,@NotBlank会忽略字符串尾部的空格

@NotNull
The annotated element must not be null. Accepts any type.
支持任何类型。
#####2.实例

/**
 * 用户ID
 */
@NotNull
private Long userId;
/**
 * 收货人姓名
 */
@Length(max=20, message="用户名长度超出20")
private String userName;
/**
 * 收货人地址
 */
@Length(max=200, message="收货人地址长度超出200")
private String userAdress;
/**
 * 收货人手机
 */
@NotBlank
@Pattern(regexp="^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$", message="手机号格式不正确")
private String userMobile;

/**
 * 云存储key
 */
@URL(message="无效的URL地址")
private String pathKey;

###验证约束方法1

Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
/**
 *@Param object object to validate
 *@Param groups the group or list of groups targeted for validation (defaults to Default)
 */
Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);

if (!constraintViolations.isEmpty()) {
    StringBuilder msg = new StringBuilder();
    for(ConstraintViolation<Object> constraint:  constraintViolations){
        msg.append(constraint.getMessage()).append("<br>");
    }
    throw new RRException(msg.toString());//对RRException进行全局处理
}
Hibernate Validator 是一个基于 Java Bean Validation 规范(JSR 380)的参考实现,用于对 Java 对象的属性进行验证。你提到的 `hibernate-validator-relocation` 并不是 Hibernate Validator 官方文档或常见术语中的标准词汇,可能是与 Hibernate Validator 的迁移、依赖管理或版本更新相关的内容。 ### 可能的含义和解释: 1. **依赖迁移(Relocation)** 在 Maven 或 Gradle 中,`relocation` 通常指依赖的 `groupId` 或 `artifactId` 发生了变更。例如,Hibernate Validator 的旧版本可能使用 `org.hibernate:hibernate-validator`,而新版本可能调整为其他坐标(如 `org.hibernate.validator:hibernate-validator`)。这种情况下需要更新项目的依赖配置。 2. **版本升级或模块调整** Hibernate Validator 的某些版本可能对模块结构进行了重构(例如将核心验证逻辑拆分为多个子模块),导致需要调整依赖关系。 3. **类或包的迁移** 如果代码中直接引用了 Hibernate Validator 的内部类或包(如 `org.hibernate.validator.internal`),在版本升级时这些类可能被迁移到其他包路径,导致编译错误。 ### 解决方案示例(Maven 依赖更新): 如果遇到依赖迁移问题,可以检查最新版本的 Maven 坐标。例如: ```xml <!-- Hibernate Validator 最新版本(示例) --> <dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator</artifactId> <version>8.0.1.Final</version> <!-- 替换为实际版本 --> </dependency> ``` ### 注意事项: - 确保与 Bean Validation API 版本兼容(如 `javax.validation:validation-api` 或 `jakarta.validation:jakarta.validation-api`)。 - 如果使用 Spring Boot,依赖通常由 `spring-boot-starter-validation` 自动管理,无需显式声明 Hibernate Validator 版本。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值