是否可以使用 JPA 定义 XOR 约束?
我需要使用 JPA 对实体定义 XOR 约束,即指定您可以在 A 列或 B 列中拥有值但不能同时在两者中拥有值的约束(但至少其中之一)。似乎可以在 MsSQL 数据库上手动执行此操作,如下所示,但理想情况下我更愿意使用 JPA 注释在实体上定义此操作。
CREATE TABLE [dbo].[test01](
[i1] [int] NULL,
[i2] [int] NULL
) ON [PRIMARY]
ALTER TABLE [dbo].[test01] WITH CHECK ADD CONSTRAINT [CK_test01] CHECK
(([i1] IS NULL AND [i2] IS NOT NULL OR [i2] IS NULL AND [i1] IS NOT NULL))
ALTER TABLE [dbo].[test01] CHECK CONSTRAINT [CK_test01]
这可能吗?
I need to define an XOR constraint on an entity using JPA i.e. a constraint that specifies that you can have a value in either column A or column B but not both (but at least one of them). It seems to be possible to do this manually on the MsSQL database as follows but ideally I'd prefer to define this on the Entity using JPA annotations.
CREATE TABLE [dbo].[test01](
[i1] [int] NULL,
[i2] [int] NULL
) ON [PRIMARY]
ALTER TABLE [dbo].[test01] WITH CHECK ADD CONSTRAINT [CK_test01] CHECK
(([i1] IS NULL AND [i2] IS NOT NULL OR [i2] IS NULL AND [i1] IS NOT NULL))
ALTER TABLE [dbo].[test01] CHECK CONSTRAINT [CK_test01]
Is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在方法中定义该逻辑片段,并使用 @PrePersist 和 @PreUpdate 对其进行注释。 缺点是约束不会反映在数据库上,因此另一个应用程序(或人员)可以插入两列都为空的行。
此处提供了有关生命周期注释和实体侦听器的更多信息。
You can define that piece of logic in a method and annotate it with @PrePersist and @PreUpdate. The drawback is that the constraint won't be reflected on the DB, so another application (or person) could insert a row with nulls on both columns.
There's more information about lifecycle annotations and entity listeners here.