Spring注释验证-在更新和添加时检查唯一性 [英] Spring annotation validation - Check for unique on update vs add

查看:261
本文介绍了Spring注释验证-在更新和添加时检查唯一性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为Sport的POJO,其属性为sportID,sportName,玩家人数.使用带注释的验证,我编写了自己的注释约束来检查sportName是否已存在于数据库中.尝试添加sportName时,它的效果很好,但是,如果我尝试在不更改sportName的情况下更新球员,则验证也会失败.

I have a POJO named sport with properties sportID, sportName, number of players. Using annotated validation I wrote my own annotation constraint to check if sportName exists in the database already or not. It works great when trying to add a sportName, however if I try to update players without changing the sportName the validation fails as well.

有任何方法可以在带注释的验证中传递参数吗?例如,我想将sportID传递给sportName约束检查,以便可以在数据库查询中排除该ID.

Is there any way to pass in a parameter in annotated validation? For example I would like to pass in sportID to the sportName contraint check so that I can exclude that ID in the db query.

或者有更好的方法吗?我应该在控制器中让Spring验证输入(使用@Valid验证),然后如果没有错误,请调用validate函数检查业务规则?

Or is there a better way of doing this? In my controller should I let Spring validate inputs (with @Valid) and then if there are no errors call a validate function to check for business rules?

推荐答案

更好的方法是使用验证组. ( Spring MVC和JSR -303验证组)

A better way would be using Validation Groups. (Spring MVC and JSR-303 Validation Groups)

然后,您可以具有没有不退出验证器"的默认验证组.并有一个带有不退出验证器"的额外组.这将使您仅在需要时才触发不退出验证器". (不幸的是,Spring 3.0不直接支持该功能,因此您必须手动"开始验证)

Then you can have the default validation group without the "not exits validator". And have an extra group with the "not exits validator". This would allow you to trigger the "not exits validator" only when you need it. (Unfortunately it is not direct supported in Spring 3.0, there you have to start the validation "by hand")

另一种方法是不像字段验证器那样实现验证器,而应该像类验证器那样实现. -在此查看针对跨字段验证讨论的不同解决方案堆栈溢出问题.它将为您提供一个如何访问id字段的想法.

An other way would be not to implement the validator like a field validator, but more like a class validator. -- Have a look at the different solutions discussed for cross field validation in this Stack Overflow Question. It will give you an idea how to access the id field.

这篇关于Spring注释验证-在更新和添加时检查唯一性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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