I would use code to enforce this rule manually. The basic idea is that assembly B needs to be well encapsulated so that the client can modify its content in a public way (i.e. addB() ). Just make sure this rule is inside this method ( addB() ) so that the number of records inside collection B does not exceed the value.
A:
@Entity public class A { public static int MAX_NUM_B = 4; @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) private Set<B> b= new LinkedHashSet<B>(); public void addB(B b) { if (this.b.size() == MAX_NUM_B) { Iterator<B> it = this.b.iterator(); it.next(); it.remove(); } this.b.add(b); } public Set<B> getB() { return Collections.unmodifiableSet(this.b); } }
IN:
@Entity public class B{ @ManyToOne private A a; }
Basic moments:
- A must be the owner of the relationship.
- In A, it is not easy to return B, since the client can bypass the verification logic implemented in
addB(B b) and freely change its contents. Instead, return unmodified view B. - In @OneToMany, set
orphanRemoval to true to tell JPA to delete B records after the corresponding instances are removed from collection B.
source share