Hibernate-Working with Collection-part 1 [@ElementCollection,@JoinTable,@JoinColumn]

Now Suppose we have a requirement that we need to save a collection.

For example save all the address all the addresses where a user has lived,so this will have a collection of addresses.

Now in our example we will remove Address as attribute and add Set<Address> listOfAddresses to hold collection and remember to initialize it with HashSet() as below in our UserDetails.java.


To use collection in our class we have to annotate the attribute with @ElementCollection

Next we have to add the details in our HibernateTest.java for UserDetails user1.
Now run the application and observe the output.



At line 4 and 10,notice first hibernate has inserted in the table USER_DETAILS and then it created a new table UserDetails_listOfAddresses and has inserted UserDetails_userId as foreign key and has inserted the Address details in this table.

Entries in DataBase:



Next we will see use of annotation @JoinTable:



Here we have seen that Hibernate has created the default table  UserDetails_listOfAddresses which is not very friendly so now we will how to customize the name of the table created by Hibernate for the Addresses

We will have to use another annotation @JoinTable(name=”USER_ADDRESS”)

public Set<Address> listOfAddresses = new HashSet();


Now when you rerun the application you will find hibernate has created the USER_ADDRESS table and has inserted the records in it.




here if you notice even in the generated new table the primary key the default UserDetails_userId which is again needs to be customised. So lets see how to do that.


public Set<Address> listOfAddresses = new HashSet();





Comments are closed