具有 JPA 和 Bean 验证的唯一约束 [英] Unique constraint with JPA and Bean Validation

查看:27
本文介绍了具有 JPA 和 Bean 验证的唯一约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个带有 Bean 验证的 @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 查询(任何并发事务可以在手动检查之后但在正在进行的事务提交之前修改数据).换句话说,不可能在 Java 级别实现有效的唯一验证,从而提供验证实现.检查唯一性的唯一可靠方法是在提交事务时.

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 规范是这样总结的:

The BV spec summarizes it like this:

问题:我们应该添加@Unique会映射到@Column(unique=true)?

Appendix D. Java Persistence 2.0 integration

Question: should we add @Unique that would map to @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 验证异常中包含唯一(和非空)约束违规会很好,但目前情况并非如此.

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)

    这篇关于具有 JPA 和 Bean 验证的唯一约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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