@CollectionId example

In our previous example we have seen how to persist collection of objects. As you can see the other table that hibernate has generated is "UserDetails_listOfAddresses". This is clearly not user friendly name. So hibernate provides us with an option to change it. To change the name we can make use of the @JoinTable(name="User_Address"). This JoinTable annotation should be given before the declaration of the collection object. Similary we can change the name of the column "UserDetails_UserId" to a more user friendly name as shown below:
@ElementCollection
@JoinTable(name="User_Address", joinColumns=@JoinColumn(name="User_Id"))
private Set
listOfAddresses = new HashSet();
Now if you closely observe, the table ""User_Address" does not have a primary key or unique key. To generate a primary key, we can make use of the annotation @CollectionId. @CollectionId is used to create a collection id. And that id will work as primary key. Bag collections id do efficiently removal and insertion of rows. The way to use @CollectionId is given in the below code. CollectionId takes few parameters as inputs. The first one is the column name with with the Id would be generated. Second is the generator which defines how a unique value is generated every time. The value "hilo-gen" is a name given to the "hilo" which is given in another annotation @GenericGenerator. The "hilo" is a generator which hibernate has given for us. The third parameter for the type of the column. For this example I have given the type as "int".
@GenericGenerator(name="hilo-gen", strategy="hilo")
@CollectionId(columns = { @Column(name="Address_Id") }, generator = "hilo-gen", type = @Type(type="int"))
private Collection
listOfAddresses = new ArrayList
();
Add the above code in the UserDetails.java class of previous example i.e. Persisting collection of objects and then execute CollectionObjectsExample.java and you get the below output. As you can see the table User_Address has a new column "Address_Id". This is the new column that the annotation @CollectionId has generated.

No comments:

Post a Comment