@ElementCollection VS @OneToMany in Hibernate

Sakshi Khandelwal
Nerd For Tech
Published in
2 min readJul 31, 2020

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 :)

If you liked this post, please clap for it. It will be really appreciating for me.

Twitter: https://twitter.com/SakshiKhandlwl
LinkedIn: www.linkedin.com/in/sakshikhandelwal276

--

--

Sakshi Khandelwal
Nerd For Tech

Java 8 Certified | AWS Certified Developer-Associate| SSE at MasterCard | Learner