如何防止更新时进行Spring验证 [英] How to prevent Spring validation on update

查看:32
本文介绍了如何防止更新时进行Spring验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为唯一的电子邮件做了一个自定义验证注释(当用户注册自己时,程序会检查数据库中是否已经有电子邮件).

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)?

所有验证注释都在同一个User Bean中.

All validation annotations are in the same User bean.

谢谢.

推荐答案

我将假设您正在使用 javax.validation .

首先,您需要一个 OnUpdate接口:

javax.validation.groups.Default

public interface OnUpdate extends Default {}

现在,您需要设置 all 只需要在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆