开发者

Is it possible to define an XOR constraint using JPA?

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 usin开发者_Go百科g 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜