如何防止更新时的 Spring 验证 [英] How to prevent Spring validation on update
问题描述
我为唯一的电子邮件做了一个自定义验证注释(当用户自己注册时,程序会检查电子邮件是否已经在数据库中).
I made a custom validation annotation for unique email (When user registers itself, program checks if email is already in database).
一切正常,但是当我需要修改用户信息而不是创建新信息时,我遇到了电子邮件已在使用中"的问题
Everything works just fine, but when I need to modify user's info and not to create a new one I run into a problem that says "Email is already in use"
我能否以某种方式仅关闭 @UniqueEmail
验证(我需要其他的,如电子邮件模式和密码验证)?
Can I somehow turn off only @UniqueEmail
validation(I need the others like email pattern and password validation)?
所有验证注解都在同一个用户 bean 中.
All validation annotations are in the same User bean.
谢谢.
推荐答案
我假设您正在使用 javax.validation
.
首先你需要一个接口 OnUpdate
:
javax.validation.groups.Default
public interface OnUpdate extends Default {}
现在您需要设置所有需要仅在UPDATE
上运行的注释:
Now you need to set all the annotations that need to only run on UPDATE
:
@NotNull(groups = OnUpdate.class)
现在,您已将验证分为两组,分别位于 OnUpdate
和 Default
中.运行 Default
将包括 OnUpdate
中的那些作为 OnUpdate
扩展 Default
.
Now, you have divided your validations into two groups, those in OnUpdate
and those in Default
. Running Default
will include those in OnUpdate
as OnUpdate
extends Default
.
现在,这是有点棘手的地方 - 您需要告诉框架在每个任务上运行哪些验证.
Now, this is where it gets a little tricky - you need to tell the framework which validations to run on each task.
如果使用 JPA,您只需要设置以下属性:
If using JPA you just need to set the following property:
javax.persistence.validation.group.pre-update = com.my.package.OnUpdate
这篇关于如何防止更新时的 Spring 验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!