问题描述
我想在Bean Validation中使用 @Unique
约束,但标准不提供。如果我使用JPA的 @UniqueConstraint
,我就没有独特的验证和错误报告机制。
I'd like to have a @Unique
constraint with Bean Validation, but that is not provided by the standard. If I would use JPA's @UniqueConstraint
I wouldn't have a unique validation and error reporting mechanism.
是否有一种定义 @Unique
作为Bean Validation约束并将其与JPA组合的方法,以便JPA创建一个具有唯一约束的列并检查值是否唯一?
Is there a way to define @Unique
as a Bean Validation constraint and combine it with JPA, such that JPA creates a column with an unique constraint and checks wheter a value is unique or not?
推荐答案
除非您获得整张桌子的锁定,否则基本上无法检查使用SQL查询的unicity(任何并发事务都可以在手动检查之后但在提交正在进行的事务之前修改数据)。换句话说,不可能在Java级别实现有效的唯一验证,从而提供验证实现。检查unicity的唯一可靠方法是提交交易。
Unless you acquire a lock on a whole table, it is basically not possible to check for unicity using a SQL query (any concurrent transaction could modify data after a manual check but before the commit of the ongoing transaction). In other words, it isn't possible to implement a valid unique verification at the Java level and thus to provide a validation implementation. The only reliable way to check for unicity is while committing the transaction.
BV规范总结如下:
问题:我们应该添加@Unique,
会映射到@Column(unique = true)吗?
@Unique无法可靠地在Java
级别进行测试,但可能会生成
数据库唯一约束生成。
@Unique今天不属于BV规范
。
@Unique cannot be tested at the Java level reliably but could generate a database unique constraint generation. @Unique is not part of the BV spec today.
所以虽然我同意它会是很高兴在Bean Validation异常中包含唯一(和非null)约束违规,目前情况并非如此。
So while I agree that it would be nice to have unique (and non null) constraint violations wrapped in a Bean Validation exception, this is currently not the case.
- Bean验证规范(JSR 303)
- Bean Validation specification (JSR 303)
- Appendix D. Java Persistence 2.0 integration
这篇关于JPA和Bean Validation的唯一约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!