Say I have an entity like this
@Entity
Class A{
//fields
@Onetomany
Set<B> b; //
}
Now, how do I limit the number of ‘B’s in the collection in such a way that, when there is a new entry in the collection, the oldest one is removed, some thing like removeEldestEntry we have in a LinkedHashMap.
I am using MySQL 5.5 DB with Hibernate. Thanks in advance.
EDIT
My goal is not to have more than N number of entries in that table at any point of time.
One solution I have is to use a Set and schedule a job to remove the older entries. But I find it dirty. I am looking for a cleaner solution.
I would use the code to manually enforce this rule. The main idea is that the collection B should be well encapsulated such that client only can change its content by a public method (i.e
addB()) . Simply ensure this rule inside this method (addB()) to ensure that the number of entries inside the collection B cannot larger than a value.A:
B:
Main points:
addB(B b)and change its content freely.Instead , return an unmodifiable view of B .orphanRemovalto true to tell JPA to remove the B ‘s DB records after its corresponding instances are removed from the B collection.