What is difference between @Entity and @embeddable

Sanjeev Yadav picture Sanjeev Yadav · Jan 15, 2014 · Viewed 36.9k times · Source

The difference between @entity and @embeddable annotation when each one is added before class declaration?

  1. the first create class as an entity, second insert column from another table?
  2. the first create class as an table, while second is embedded in another class?
  3. the first sets standard as a class, second define table type
  4. the first create table for that class, second embed something into different class
  5. the first define table property, second create union of two tables

Answer

Sazzadur Rahaman picture Sazzadur Rahaman · Jan 15, 2014

@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