Hibernate @Embeddable and @Embedded Annotation (original) (raw)

Last Updated : 24 Apr, 2025

The @Embeddable and @Embedded annotations in Hibernate are used to map an object’s properties to columns in a database table. These annotations are used in combination to allow the properties of one class to be included as a value type in another class and then be persisted in the database as part of the containing class.

Overview

Benefits

The main benefits of using the @Embeddable and @Embedded annotations in Hibernate are:

  1. Code Reusability: You can reuse the embeddable class in multiple entities, avoiding duplication of code.
  2. Normalization: It helps in normalizing the database by reducing the number of tables, which in turn improves the performance.
  3. Data Integrity: It ensures data integrity by maintaining the relationship between the embeddable and the containing class.
  4. Simplicity: It simplifies the development process by reducing the number of classes and tables required to map the data.
  5. Better Data Modelling: It allows for better data modeling by allowing you to encapsulate the properties of an object within another object, making the data structure more intuitive and easy to understand.
  6. Ease of maintenance: it makes the maintenance of the codebase more manageable and easy.
  7. Flexibility: The embeddable classes can be used in multiple entities, and it also supports complex data modeling with the use of @Embedded and @AttributeOverrides.
  8. Readability: The use of @Embeddable and @Embedded annotations makes the code more readable and self-explanatory.
  9. Performance: it improves the performance of the application by reducing the number of joins required to fetch the data.
  10. Business logic: It allows to encapsulation of the business logic within the embeddable class, making it more manageable and easy to understand.

Example

Embeddable Class:

Java `

@Embeddable public class Address { private String street; private String city; private String state; private String zip; // getters and setters }

`

Entity Class:

Java `

@Entity public class Employee { @Id private int id; private String name; @Embedded private Address address; // getters and setters }

`

Note: You can also use the @AttributeOverrides to customize the column name mapping.

Java `

@Embedded @AttributeOverrides({ @AttributeOverride(name = "street", column = @column(name = "home_street")) }) private Address address;

`

The above example will map the street property of the Address class to home_street in the database table.

Conclusion

Similar Reads

Basics of Spring Framework








Software Setup and Configuration









Core Spring



























































































Spring with REST API



Spring Data












Spring JDBC








Spring Hibernate