The difference between @entity and @embeddable annotation when each one is added before class declaration?
@Entity
annotation over a class defines that, it has a distinct separate existence. Thus we can run DB queries, without being dependent on any other class. @Embeddable
annotation over a class defines that, it does not have independent existence. Thus we cannot run DB queries, without depending on other class. Here is an example to understand it better:
@Entity
User
-- long id
-- String name
-- String email
@Embedded
-- UserDetails userDetail
@Embeddable
UserDetails
-- Date dateOfBirth
-- String sex
-- String address
-- String maritalStatus
Here you can see without having a User
, UserDetails
is useless.
Generally, in OOP, we first design the classes and then we design database entities. For some classes (like UserDetails class in the above example), we do not want to have separate tables in DB, where their independent existence is meaningless. In those cases, we mark the class as embeddable.
Typically, embeddable classes share the same table as the Entity in which they are embedded