Hibernate collection mapping
Hibernate supports collection mapping as value type.
The interfaces supported by it are as follows:
1. Set
2. List
3. Map
4. Sorted Set
5. Sorted List
6. Sorted Map
All these are defined under java.util package. So we need to import java.util package to use them.
Collection mapping can be performed as
1. Persistent Collection : The Persistent collections contains almost all Hibernate type ie Basic Type, Custom type, Components and references to other entities.
The Object in a collection is handled with "value". The collection instances have usual behaviour ie they are persisted automatically when they are referred by a persisted object and like wise they are deleted when unreferenced.
Note: Two entities can't share a reference to same collection instance.
2. Indexed Collections :
Lists:
We can map Lists as ordered list ,in this the order doesn't matter in the database and as indexed list where order is important in the database.
To store the index value in a particular column ,we have to use @javax.persistence.Column_name annotation in the property.
Maps:
The question with Maps is where the key value is stored?There are several options. Maps can borrow their keys from one of the associated entity properties or have dedicated columns to store an explicit key.
3. Bidirectional Associations in Hibernate Collection
It allows navigation from both ends of the association.There are two types of bidirectional association
1. One to many : it set or bag value at one end and single value at the other end.
To use one of the target entity property as a key of the map, use @MapKey When using @MapKey without the name attribute, the target entity primary key is used. The map key uses the same column as the property pointed out.
2. Many to Many: it set or bag value at both ends.
Ques : What is the main difference between the Set and Bag collections in Hibernate?
Ans: A bag is an unordered collection ,it contain duplicate elements, that means during retrival order can change. Note: Corresponding to bag we use java.util.List .
set can contain only unique objects.When a same element is added , it will replace the old one.
Note: Corresponding to set we use java.util.Set.