Hibernate : Differences in @one-To-Many relation and @ElementCollection

This is for sure that to maintain one to many relation we need to have a collection reference in the source object class. Then what is the difference between the two ?

In simple words, a join table will always get created when using @ElementCollection, however the join table can be avoided if

    @OneToMany(mappedBy = “driver”) here drive is the member variable from other entity.

image

How to decide what kind should be used when ?

I believe @ElementCollection is mainly for mapping non-entities (embeddable or basic) while @OneToMany is used to map entities. So which one to use depend on what you want to achieve.

ElementCollection is a standard JPA annotation, which is now preferred over the proprietary Hibernate annotation CollectionOfElements.

It means that the collection is not a collection of entities, but a collection of simple types (Strings, etc.) or a collection of embedded elements (class annotated with @Embedded).

It also means that the elements are completely owned by the containing entities: they’re modified when he entity is modified, deleted when the entity is deleted, etc. They can’t have their own lifecycle.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s