Saving Collections in Hibernate – @ElementCollection

Saving Collections in Hibernate – @ElementCollection
In our previous examples we had seen how to embed one entity into another, how to change the column names using annotations.

In this example we are going to see how to save collections using Hibernate. For saving collections in database using hibernate, we are going to use the annotation @ElementCollection

Structure
structure

hibernate.cfg.xml

NewHibernateUtil.java

address.java

employee.java

We have used couple of new annotations here,
1. @ElementCollection – Used to indicate the hibernate that we are using another entity as collection
2. @JoinTable – This is optional, this is used to set the table name. If this is not mentioned, By default hibernate creates a table with name entityclass_collectionclass (Here – employee_address). Since we have mentioned the name as Address_Collection, table will be created on that name

Execution.java

Output:

op1

Here we can see hibernate creates 2 tables, Employee table and Address_Collection
Employee class has same data, the employee ID (Which we have mentioned as auto generated field), Employee_ Name and Employee_Password.

Address_Collection table takes the Employee_ID (Primary key of Employee table) as Foreign key and assigns the list of address for that ID.

Employee Table

op2

Address_Collection Table

op3

Here we can see that, Employee_ID (Primary key of Employee table) is considered as foreign key and corresponding address are saved in Address_Collection table

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *