Sub topic 5
Embeddables, enums and other value types
This chapter assumes you can map a basic @Entity with an @Id and @Column fields, as covered in the earlier chapters. It shows how to model values that have no identity of their own: grouped fields, enums, and a few common types such as dates and money.
Value types versus entities
An entity has an identifier and its own row. A value type has no identifier. It exists only as part of an entity, and its fields are stored as columns in the owner's table. An address or a price range is a typical example.
Embeddables
Mark a class with @Embeddable and use it in an entity with @Embedded. The fields become columns of the owning table.
import jakarta.persistence.*;
@Embeddable
public class Address {
@Column(name = "street")
private String street;
@Column(name = "city")
private String city;
@Column(name = "postal_code", length = 10)
private String postalCode;
protected Address() {
}
public Address(String street, String city, String postalCode) {
this.street = street;
this.city = city;
this.postalCode = postalCode;
}
public String getStreet() { return street; }
public String getCity() { return city; }
public String getPostalCode() { return postalCode; }
}An embeddable needs a no-argument constructor, which may be protected, just like an entity.
If you embed the same class twice in one entity, the column names collide. Use @AttributeOverride to rename them.
import jakarta.persistence.*;
@Entity
@Table(name = "customers")
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Embedded
@AttributeOverride(name = "street", column = @Column(name = "billing_street"))
@AttributeOverride(name = "city", column = @Column(name = "billing_city"))
@AttributeOverride(name = "postalCode", column = @Column(name = "billing_postal_code"))
private Address billingAddress;
@Embedded
private Address shippingAddress;
@Enumerated(EnumType.STRING)
@Column(nullable = false, length = 20)
private CustomerStatus status = CustomerStatus.ACTIVE;
protected Customer() {
}
public Customer(Address billingAddress, Address shippingAddress) {
this.billingAddress = billingAddress;
this.shippingAddress = shippingAddress;
}
public Long getId() { return id; }
public Address getBillingAddress() { return billingAddress; }
public Address getShippingAddress() { return shippingAddress; }
public CustomerStatus getStatus() { return status; }
public void setStatus(CustomerStatus status) { this.status = status; }
}public enum CustomerStatus {
ACTIVE,
SUSPENDED,
CLOSED
}If every field of an embedded object is null, Hibernate loads the whole embedded property as null, not as an empty object. Check for this before calling methods on it.
Enums
By default, JPA stores an enum by its ordinal, which is its position in the declaration. That default is fragile.
| Mapping | Stored value | Risk |
|---|---|---|
| `EnumType.ORDINAL` (default) | `0`, `1`, `2` | Reordering or inserting constants silently changes the meaning of existing rows. |
| `EnumType.STRING` | `"ACTIVE"` | Renaming a constant breaks existing rows, but reordering is safe. |
Other value types
- Dates and times: use
java.timetypes such asLocalDate,LocalDateTimeandInstant. Hibernate maps them without extra annotations. - Money: use
BigDecimalwith@Column(precision = 12, scale = 2). Never usedoublefor money. - Long text: use
@Lobor a column definition suited to your database. - Fields to skip: mark a field
@Transientto keep it out of the table. - Custom conversion: implement an
AttributeConverterand annotate it with@Converterto store a type in a different form, such as a wrapper object stored as a string.
import jakarta.persistence.*;
import java.math.BigDecimal;
import java.time.LocalDate;
@Entity
public class Invoice {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(precision = 12, scale = 2, nullable = false)
private BigDecimal total;
private LocalDate issuedOn;
@Transient
private String displayLabel;
protected Invoice() {
}
}Exercise
A Customer has two embedded Address fields, and its status enum uses the default @Enumerated setting. Name the two changes needed so the table has distinct address columns and enum values survive reordering of the enum constants.
Show answer
Add @AttributeOverride annotations on one of the @Embedded address fields so its columns get different names, and annotate the enum field with @Enumerated(EnumType.STRING) so the constant name is stored instead of its ordinal.