Home > AI > Backend > SpringBoot > mysql-connector-java >

@Embeddable

 how we can map one entity that contains embedded properties to a single database table.

So, for this purpose, we’ll use the @Embeddable and @Embedded annotations provided by the Java Persistence API (JPA).

Company.java

The company table will store basic information such as company name, address, and phone, as well as the information of a contact person:

public class Company {

    private Integer id;

    private String name;

    private String address;

    private String phone;

    private String contactFirstName;

    private String contactLastName;

    private String contactPhone;

    // standard getters, setters
}

The contact person, though, seems like it should be abstracted out to a separate class. The problem is that we don’t want to create a separate table for those details. So, let’s see what we can do.

@Embeddable
public class ContactPerson {

    private String firstName;

    private String lastName;

    private String phone;

    // standard getters, setters
}
@Entity
public class Company {

    @Id
    @GeneratedValue
    private Integer id;

    private String name;

    private String address;

    private String phone;

    @Embedded
    private ContactPerson contactPerson;

    // standard getters, setters
}

As a result, we have our entity Company, embedding contact person details, and mapping to a single database table.

We still have one more problem, though, and that is how JPA will map these fields to database columns.

we can use @AttributeOverrides and @AttibuteOverride to override the column properties of our embedded type.

@Embedded
@AttributeOverrides({
  @AttributeOverride( name = "firstName", column = @Column(name = "contact_first_name")),
  @AttributeOverride( name = "lastName", column = @Column(name = "contact_last_name")),
  @AttributeOverride( name = "phone", column = @Column(name = "contact_phone"))
})
private ContactPerson contactPerson;

Leave a Reply