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.
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])
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])
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.
@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.
精彩评论