Hibernate – Difference Between List and Bag Mapping
Hibernate supports both List and Bag Mapping and Set Mapping too. Hence there will be a tradeoff, regarding which is the best data type to use. The choice will be purely based on requirements but still, let us see the differences between them. Whenever there is a one-to-many relationship or many-to-many relationship etc., necessity, we need to have either List or Bag Mapping.
Let us see the configuration files while using List Mapping
Let us see the configuration files while Bag Mapping.
In production deployment requirements or for the live product, from the performance point of view, we need to go for Bag mapping as the best choice. As List mapping requires ordering, database operations slow down the queries and it will take a lot of time to display the data. On the other hand, Bag mapping is the better choice and whenever there is a need for ordering, we may need to use the JPQL query with an ‘order by’ clause. Let us see the differences with Set as well with respect to database operations and hibernate
|It is unordered||Will not allow duplicates|
|It is ordered||Will allow duplicates|
|It is unordered||Will allow duplicates|
|java.util package contains List.||java.util package does not contain Bag.|
|In Hibernate, by using java.util.List we can map List.||In Hibernate, by using java.util.List we can map Bag.|
|List is ordered and may have duplicates.||Bag is unordered and allows duplicates.|
|This approach slows down the database operations as retrieving the associations in an ordered manner will affect the performance.||This is an efficient approach as retrieving the associations like (one to many or many to more) in an unordered manner provides better performance.|
|By default, we get ordered results but performance-wise slow.||In order to achieve order, we may need to use JPQL Query with an order by but only when needed we can do it, and hence it is an additional one.|
|In older Hibernate versions (Prior to 5.0.8), while using java.util.List and merge parent entity, Hibernate generated 2 insert statements for each new child entity.||It does not require an index element and is almost similar to List only. While comparing with List, Bag is preferred.|
|For many-to-many associations, handling List mapping is a poor practice. Set Mapping is the better choice.||Almost Bag behaves the same way as Set and depends upon the requirement, it can be decided either to go for Set or Bag|
|A sequence element is needed.||No need for a sequence element.|
Please Login to comment...