Advertise with us

Our eBooks

Embedding Entities in other Entities

In this tutorial you will show how to map composite components using Hibernate/JPA Annotations.  Consider the following relationship between Worker and WorkerInfo Entity.

embeddable hibernate jpa embed

According to the relationship each Worker should have a unique WorkerInfo.

So, since the two Entities are strongly related (composition relation), it is better to store them in a single table (named Worker) but you can keep them logically separated in two Entities. Here's the Worker Entity:

package com.sample;

import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

public class Worker {

    private long workerId;
    private String name;
    private WorkerInfo info;

    public Worker() {

    public Worker(String name, WorkerInfo info) { = name; = info;

    @Column(name = "WORKER_ID")
    public long getStudentId() {
        return this.workerId;

    public void setWorkerId(long workerId) {
        this.workerId = workerId;

    @Column(name = "WORKER_NAME", nullable = false, length = 100)
    public String getName() {

    public void setName(String name) { = name;

    public WorkerInfo getWorkerInfo() {

    public void setStudentAddress(WorkerInfo info) { = info;


The @Embedded annotation is used to specify the WorkerInfo entity should be stored in the WORKER table as a component.

@Embeddable annotation is used to specify the WorkerInfo class will be used as a component. The WorkerInfo class cannot have a primary key of its own, it uses the enclosing class primary key.

package com.sample;
import javax.persistence.Column;
import javax.persistence.Embeddable;

public class WorkerInfo {

    private String address;
    private String city;
    private String country;

    public WorkerInfo() {

    public WorkerInfo(String street, String city, String state ) {
        this.address = street; = city; = state;

    @Column(name = "INFO_STREET", nullable = false, length=250)
    public String getAddress() {
        return address;

    public void setAddress(String address) {
        this.address = address;
    @Column(name = "INFO_CITY", nullable = false, length=50)
    public String getCity() {
        return city;

    public void setCity(String city) { = city;
    @Column(name = "INFO_COUNTRY", nullable = false, length=50)
    public String getCountry() {
        return country;

    public void setCountry(String country) { = country;


© 2021 All Rights Reserved.

Please publish modules in offcanvas position.