简体   繁体   English

如何用JPA表达此约束?

[英]How do I express this constraint with JPA?

I have a class that looks like this: 我有一堂课,看起来像这样:

public enum Scope {
  A, B, C...
}

@Entity
public class User {

    ...

    Scope scope; // enum, see above

    @ElementCollecton
    List<Long> numbers;

    ...
}

My problem is that I don't know how to express the following constraint with either JPA or directly in my Postgres database: There can only be one User with a scope x who has a number y. 我的问题是我不知道如何用JPA或直接在我的Postgres数据库中表达以下约束: 只能有一个范围为x的用户,其数字为y。

In order to clarify what I mean, some pseudocode: 为了澄清我的意思,一些伪代码:

This is valid (Bobs 3 does not colide with Toms 3 since Bob has a different scope): Tom(scope=A,numbers=[1,2,3,4]), Carl(scope=A,number=[5,6,7]), Bob(scope=B,numbers=[3, 42, 100]) 这是有效的(因为Bob的作用域不同,Bobs 3不会与Toms 3发生冲突):Tom(scope = A,numbers = [1,2,3,4]),Carl(scope = A,number = [5, 6,7]),鲍勃(scope = B,numbers = [3,42,100])

But this is invalid (Carls 4 violates the constraint since Tom has the same scope and also a 4 in his list): Tom(scope=A,numbers=[1,2,3,4]), Carl(scope=A,number=[4,5,6,7]), Bob(scope=B,numbers=[3, 42, 100]) 但这是无效的(Carls 4违反了约束,因为Tom具有相同的作用域,并且列表中还有一个4):Tom(scope = A,numbers = [1,2,3,4]),Carl(scope = A, number = [4,5,6,7]),Bob(scope = B,numbers = [3,42,100])

Thanks for your help, Fabian 感谢您的帮助,Fabian

One thing you can do is lie to JPA about the foreign key to the element collection and then put an ordinary unique constraint on the combination of scope + number in the collection table. 您可以做的一件事情就是向JPA求助于元素集合的外键,然后对集合表中范围+数字的组合施加一个普通的唯一约束。

@Column(name="SCOPE")
@Enumerated(EnumType.STRING)//or whatever
private Scope scope;

@ElementCollection
@CollectionTable(name= "NUMBERS" ,
    joinColumns={ @JoinColumn(name = "USER_ID", referencedColumnName = "ID"),
                  @JoinColumn(name = "USER_SCOPE", referencedColumnName = "SCOPE") }),
@Column(name="NUMBER")
private List<Long> numbers;

Obviously USER_SCOPE is totally unnecessary in the normalized model, but by telling JPA it's part of the key you can trick the provider into maintaining the column for you. 显然,在规范化模型中USER_SCOPE完全不必要,但是通过告诉JPA这是密钥的一部分,您可以欺骗提供程序为您维护该列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM