One of the things that we need to take into account when creating a @OneToMany annotation is the performance. By default this is a lazy loaded collection and only if we need to get the values we will have a second hit to the database to retrieve it. But, we can avoid some hits to the database if we choose wisely the type of the collection. For example, if we map the collection to a Set then every time we need to add a new element to this collection, we need to retrieve the existing elements associated to our persistent object to validate that the newly added element of the collection is unique. If we had mapped it as a List then we could have added the new element and Hibernate would not have retrieved the previously added elements because a List allows duplicates.
Sets are still the preferred collection mapping if the above scenario is not that common in our code and the duplicates should not be allowed. Especially for certain Hibernate versions we need to be extra careful in using Lists with bi-directional mapping and cascadeType.ALL. The bug which was solved on Hibernate 5.0.8, inserts duplicate entries of the same child element so the Set is preferred in order to avoid this bug.
Sets are still the preferred collection mapping if the above scenario is not that common in our code and the duplicates should not be allowed. Especially for certain Hibernate versions we need to be extra careful in using Lists with bi-directional mapping and cascadeType.ALL. The bug which was solved on Hibernate 5.0.8, inserts duplicate entries of the same child element so the Set is preferred in order to avoid this bug.
Comments
Post a Comment