Hibernate-Working with Collection-part 2 [adding primary key]

This post is in continuation to our previous post where we have added a List of address

Now we wish to define a Primary key so that we can put an index on the table generated by Hibernate.
so for that the data type of the Address should be the one that supports indexes.
ArrayList is a good option as it supports indexes,so we will change our address from Set to Collection

We will be using the interface Collection and not the Arraylist while defining the listOfAddresses as

private Collection<Address> listOfAddresses = new ArrayList<Address>();

next generate the getters and setters.

Next is we need to define the primary key configuration and the way to do that is by using the @CollectionId annotation.
@CollectionId is Hibernate Specific and its not from JPA.
Below are the attributes of @CollectionId

@CollectionId(columns = { @Column }, generator = “”, type = @Type)


  • @Column is the will be used for then name of primary key column.
  • generator would be the sqeuence generator stratergy and
  • @Type will be the data type of the column.

For generator we will have to add @GenericGenerator
@GenericGenerator(name = “sequence-gen”, strategy = “sequence”)

“sequence-gen” is the one of the generator that hibernate provide with strategy as “sequence”

So will all the annotation it will look like below

@CollectionId(columns = { @Column(name=”ADDRESS_ID”) }, generator = “sequence-gen”, type = @Type(type=”long”))
private Collection<Address> listOfAddresses = new ArrayList<Address>();






Now when we run the code we will get below output.

Notice  line 6 in above image

Hibernate: create table USER_ADDRESS (USER_ID int4 not null, USER_CITY varchar(255), USER_PINCODE varchar(255), USER_STATE varchar(255), USER_STREET varchar(255), ADDRESS_ID int8 not null, primary key (ADDRESS_ID))


This will insert a primary key column in Database




Comments are closed