Java – @embeddable vs @entity for a mapping a collection

hibernatejavajpaormspring

This must be quite naive but I have a doubt on when to use @Entity and @Embeddable.

Say I have a User and Notification class.

 @Entity
 public class User{
     //other properties
     @onetomany
     private List<Notification> notifications;
 }

 @Entity
 public class Notification{
     //properties
 }

I understand that there will be tables for class User and Notification, and a third table for mapping.
What if I do it like this?

 @Entity
 public class User {
     //other properties
     @ElementCollection
     private List<Notification> notifications;
 }

 @Embeddable
 public class Notification{
     //properties
 }

I know this won't create a table for Notification. But I can still store my notification objects. I went through the documentation, but couple of doubts:

  1. Is it based on whether I want to see class B as a seperate table?
  2. Is there a performance difference b/w creating a table and an embeddable object?
  3. What can I not do with embeddable object that I can do with a table other than directly querying the table?

NOTES

For anyone reading this question, this question too might help you.

Best Answer

  1. Is it based on whether I want to see class B as a separate table?

Yes, when you use @Embedded, You embed that @Embeddable entity in @Entity class, which makes it to add columns for embedded entity in same table of @Entity class.

  1. Is there a performance difference b/w creating a table and an embeddable object?

When you use @Embedded, for table creation, one query is required, also for inserting and selecting a row. But if you don't use it, multiple queries are required, hence, use of @Embedded yields more performance, we can say.

  1. What can I not do with embeddable object that I can do with a table other than directly querying the table?

Removing the respective embedded entity may be, but there may be integrity constraint violations for this.