Skip to content

Latest commit

 

History

History
131 lines (88 loc) · 2.4 KB

embeddable.rst

File metadata and controls

131 lines (88 loc) · 2.4 KB

Embeddable classes

Embeddable classes group the properties for ../entity.

Embeddable definition

The following code snippet shows how to define an embeddable:

@Embeddable
public class Address {

    final String city;

    final String street;

    @Column(name = "ZIP_CODE")
    final String zip;

    public Address(String city, String street, String zip) {
        this.city = city;
        this.street = street;
        this.zip = zip;
    }
}

The embeddable class is used as the entity field type:

@Entity
public class Employee {
    @Id
    Integer id;

    Address address;
}

The above entity definition is equivalent to following one:

@Entity
public class Employee {
    @Id
    Integer id;

    String city;

    String street;

    @Column(name = "ZIP_CODE")
    String zip;
}

Note

In Java 14 and later version, you can annotate records with @Embeddable:

@Embeddable
public record Address(
  String city,
  String street,
  @Column(name = "ZIP_CODE")String zip) {
}

Naming convention

A naming convention is inherited from the enclosing ../entity.

Field definition

By default, the fields are persistent and correspond to the database columns or result set columns.

The field type must be one of the following:

  • basic
  • domain
  • java.util.Optional, whose element is either basic or domain
  • java.util.OptionalInt
  • java.util.OptionalLong
  • java.util.OptionalDouble
@Embeddable
public class Address {
    ...
    String street;
}

Column

You can specify the corresponding column name with the @Column annotation:

@Column(name = "ZIP_CODE")
final String zip;

Transient

If an embeddable has fields that you don’t want to persist, you can annotate them using @Transient:

Method definition

There are no limitations in the use of methods.

Example

Employee employee = new Employee(); // Entity
Address address = new Address("Tokyo", "Yaesu", "103-0028"); // Embeddable
employee.setAddress(address);