Hibernate Collections

hibernate

// @ElementCollection 

Hibernate support Collections (field-level annotation):

@ElementCollection
private List<Address> listOfAddresses = new ArrayList<Address>();
...
Address addr1 = new Address(); ...
Address addr2 = new Address(); ...
user.getListOfAddresses().add(addr1);
user.getListOfAddresses().add(addr2);

When we save the user model object to the database, Hibernate creates the 
UserDetails_listOfAddresses table with the foreign key UserDetails_userId.

To tell Hibernate to use eager loading for this collection:

@ElementCollection(fetch=FetchType.EAGER)
@JoinTable(name="USER_ADDRESS", joinColumns=@JoinColumn(name="USER_ID"))
private Collection<Address> listOfAddresses = new ArrayList<Address>();

// @CollectionId

@CollectionId(columns = { @Column(name="ADDRESS_ID") }, 
              generator="hilo-gen", type = @Type(type="long"))

In the above code, we tell Hibernate to generate a primary key for the collection table.  Here we 
tell Hibernate to use ADDRESS_ID as the primary key for the ADDRESS  table, and the data type 
for this primary key column should be of type "long".   We use the hilo strategy for generating the 
value for this primary key column.  The hilo strategy is provided by Hibernate.

@GenericGenerator(name="hilo-gen", strategy="hilo")
@CollectionId(columns = { @Column(name="ADDRESS_ID") }, generator="hilo-gen", type = @Type(type="long"))
private Collection<Address> listOfAddresses = new ArrayList<Address>() 

The Address class is still an embedded class, marked with the @Embedded annotation

// Control the name of the join table:

@ElementCollection
@JoinTable(name="USER_ADDRESS")
private List<Address> listOfAddresses = new ArrayList<Address>();

// Control the name of the join column:

@ElementCollection
@JoinTable(name="USER_ADDRESS", joinColumns=@JoinColumn(name="USER_ID"))
private List<Address> listOfAddresses = new ArrayList<Address>();

// CascadeType.ALL:
This tells Hibernate that what ever happens to the other object should be cascaded. 
For example, if the user is deleted, all the vehicles owned by that user should also 
be deleted, and if the user is persisted, Hibernate should automatically persist all 
the vehicles that are owned by that user.
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License