Collection elements are much needed to have one-to-many, many-to-many, relationships, etc., Any one type from below can be used to declare the type of collection in the Persistent class. Persistent class from one of the following types:
- java.util.List
- java.util.Set
- java.util.SortedSet
- java.util.Map
- java.util.SortedMap
- java.util.Collection
Let us see where can we use List, Set, and Map by seeing the differences among them
List |
Set |
Map |
---|---|---|
Duplicates are allowed. | Duplicates are not allowed. | Duplicates are not allowed. |
Insertion order is maintained. | Insertion order is not maintained. | Insertion order is not maintained. |
Index element helps to identify an element in the list. Hence need to use this whenever the index is possible and it is mandatory. | For uniquely maintaining the collection of elements, we can go for the set. | As a key/value pair pattern means we can go for Map. |
Mapping List
POJO class
Java
|
XML
XML
|
In the main java file where we can do CRUD operations, we have to associate a List as follows
Main java file
Java
|
Not only List, but we can also use Bag, Set, and Map in the collections.
Mapping Bag
This is almost similar to List but the index element is not needed
Example of POJO class
Java
|
In Hibernate Mapping, it differs from the List
XML
|
The Main Java file is similar to the one that is used for the list.
Major difference between List and Bag: In List, the index element is mandatory, and order is maintained. In Bag, there is no index element and hence no order.
Mapping Set
XML
XML
|
POJO class
Java
|
Main java file
Java
|
Mapping Map
XML
XML
|
POJO class
Java
|
Main java file
Java
|
SortedSet and SortedMap by the name itself we can come to know that if a set is sorted(ascending order by default)/a map is sorted(ascending order by default)
Mapping SortedSet
POJO class
Java
|
XML
XML
|
Main java file
Java
|
Similarly, SortedMap is similar to the map and by default, it follows natural sorting order or we can customize that
Mapping SortedMap
POJO class
Java
|
XML
XML
|
Main Java file
Java
|
Conclusion
By using different patterns, according to the requirements, we can use collection mapping in hibernate.
- For ordering, use List
- For uniqueness, use Set
- For key-value maintenance use Map
- Using SortedMap/SortedSet is not an ideal solution as it will degrade performance. Instead, we can go for JPQL and add an Order By clause.