Nerd For Tech
Published in

Nerd For Tech

@ElementCollection VS @OneToMany in Hibernate

What does this mean for you?

Well, first we are going to understand each concept one by one.

@ElementCollection

In the simplest term, @ElementCollection tells the compiler that we are mapping a collection, in which, @CollectionTable gives the name of the target table and then @JoinColumn specifies the actually column we join on like below:

1`

It defines the relationship in following ways:

  • One-To-Many relationship to an @Embeddable object
  • One-To-Many relationship basic objects like Java primitives, wrapper, Date, String, etc.

@ OneToMany

It defines the One-To-Many relationship when the target objects are nothing but an entity only. As seen in the below example, one instructor can have multiple courses.

Comparison:

  1. @ElementCollection on the other hand, is very similar to @ OneToMany except target object is not an Entity.
  2. With @ElementCollection, we can’t query, persist or merge target object independently of their parent object.
  3. It doesn’t support cascade operation. It means target object are always persisted, merged, removed with their parent object.
  4. So, @ElementCollection is an easy way to define a collection with simple/basic objects. @ OneToMany is the best for complex use-case in which fine-grained control is required.

Hope you like it.

Follow me for New Articles on AWS, Java, Spring, Hibernate

Stay Connected :)

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store