Other Tutorials

JPA @Embeddable and @Embedded

Introduction:

As an object-oriented developer, we want to avoid having larger classes with tons of unrelatable fields. And so, we might often feel the need to represent a JPA Entity using multiple objects.

In this quick tutorial, we’ll learn how to achieve it using @Embedded and @Embeddable annotations in JPA or Hibernate.

Context Buildup:

Let’s say we have a person table with the following columns:

And we want to map it as a JPA Entity.

Mapping so many properties directly in our entity class doesn’t feel that natural to our developer instinct. Also, changing the database table structure is not a viable option. What do we do?

@Embeddable:

Let’s define a PersonName and Address classes first:

We have marked both of these with @Embeddable annotation to denote that they’ll be embedded into a JPA entity.

@Embedded:

Finally, we’ll use @Embedded annotation to embed a specific type.

Let’s define our Person entity that’ll represent our person table:

We have used @Embedded annotation here to denote that these objects will be embedded in our entity. In other words, all of these objects will together be mapped to a single person database table.

Overriding Attributes:

Embeddable objects often come handy specifically when we have multiple entities using it.

Let’s now say, we have another table – office:

The office table also has an Address type with the difference in just a few field names.

Here as well, we can use the same Address embeddable object. The idea is to override the street and pincode attributes of the Address class using @AttributeOverrides and @AttributeOverride annotations:

This approach is cleaner and saves us from having duplicate fields with just different names repeated across multiple entities. 

Rather, we can override any of the column properties of our embeddable type.

Conclusion:

In this tutorial, we explored JPA @Emdeddable and @Embedded annotations.

Be the First to comment.

Leave a Comment

Your email address will not be published. Required fields are marked *