The difference between @Entity and @Embeddable annotation when each one is added before class declaration?
@Embedded / @Embeddable allows us to easily do this without having to split the database table. Second, it allows for reuse of common mappings between entities. Say each table has a simple revision tracking, with two columns containing the username of the person who changed the row, and the time it happened.
The @Entity annotation specifies that the class is an entity and is mapped to a database table. The @Table annotation specifies the name of the database table to be used for mapping.
An entity can aggregate objects together and effectively persist data and related objects using the transactional, security, and concurrency services of a JPA persistence provider.
With Hibernate we can use the @Embeddable annotation to mark a class to be eligible as an embeddable class. We can use the @Embedded annotation to embed an embeddable class. The attributes of an embedded class can be overridden using the @AttributeOverrides and the @AttributeOverride annotations.
@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
Entities have an identity and can be queried for. Embeddables have no identity of their own and can only be queried for using the owning entities.
If you open an entity class, you will always find the @Id
annotation - it is mandatory. If you open an embeddable class, you will never find an @Id
annotation - it is forbidden.
EDIT: It is not entirely correct that embeddables can only be stored as a part of the parent, i.e. in the same table. This is only true for one-to-one relationships. You can have Collections
and Maps
of embeddable objects in the parent entity and they will be mapped to own collection tables.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With