Saturday, August 20, 2016

HIBERNATE: Saving Collections


  • Imagine a situation where you want to save the list of current and past addresses of an employee. 
  • One cannot say what would be the right number of objects. 
  • Hence, a collection of Address is to be used in this situation.

This is the element to be stored as a collection of.



Instead of using @Embedded annotation this time on the class member, we use @ElementCollection to denote the presence of a collection-type member of the class.





This upon executing the main() method as shown below will produce another table which will consist of the addresses for each user.



A new table is created combining the names of the entity class and the value object's class as show below:



The name of table may not seem very user-friendly and therefore there are ways to rename it to whatever the hell you like. 

This can be done through @JoinTable annotation. Some additional annotations can be used to rename the foreign key to the parent table, i.e. @JoinColumn(name="***")






Some additional Hibernate-native annotations can be used to add primary key to the join table created.

  • @GenericGenerator is an id generator provided by the Hibernate.
  • @CollectionId is an annotation used to add primary key column to the table created for a collection of embedded value objects inside the parent entity class.



To be Noted! As can be seen from upper screenshot, the collection data type has changed to ArrayList from Set since sets do not support indexing, which means there's no such things are indices/positions inside a set structure.






No comments:

Post a Comment