Sub topic 5
Embeddables, enums and other value types
This chapter assumes you can map a basic @Entity with @Id and @Column, and that you know what a derived query method is. It covers mapping data that has no identity of its own: groups of columns, enums, numbers, dates, and custom types.
Entities and value types
An entity has an identifier and a lifecycle. A value type has neither. It exists only as part of an entity, and it is stored in the owner's table. An address, a money amount, or a status flag is a value. Two addresses with the same street, city and postal code are interchangeable.
JPA gives you these tools for values:
| Need | Tool |
|---|---|
| Group several columns into one Java object | `@Embeddable` and `@Embedded` |
| Store a fixed set of constants | `@Enumerated` |
| Store a custom type in one column | `AttributeConverter` |
| Store numbers and dates | Standard Java types with column settings |
Embeddable classes
Mark a class with @Embeddable to make it a reusable group of columns. It has no @Id and no table of its own.
import jakarta.persistence.Column;
import jakarta.persistence.Embeddable;
import java.util.Objects;
@Embeddable
public class Address {
@Column(length = 120)
private String street;
@Column(length = 60)
private String city;
@Column(name = "postal_code", length = 12)
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; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Address other)) return false;
return Objects.equals(street, other.street)
&& Objects.equals(city, other.city)
&& Objects.equals(postalCode, other.postalCode);
}
@Override
public int hashCode() {
return Objects.hash(street, city, postalCode);
}
}Three rules apply to every embeddable:
- It needs a no-argument constructor.
protectedis enough, as with entities. - It should implement
equalsandhashCodefrom all of its fields. Unlike an entity, a value has no identifier to compare, so the field values define equality. - It should be treated as immutable. Replace the whole object instead of changing one field, because that keeps the owner's dirty checking predictable.
Using an embeddable in an entity
Add the type as a field and mark it @Embedded. The annotation is optional when the class already carries @Embeddable, but it makes the intent visible.
If you embed the same type twice, both copies would map to the same column names. Hibernate then fails at startup with a duplicate column error. Use @AttributeOverride to rename the columns for one of them.
import jakarta.persistence.*;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDate;
@Entity
@Table(name = "customers")
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
@Enumerated(EnumType.STRING)
@Column(nullable = false, length = 20)
private CustomerTier tier = CustomerTier.STANDARD;
@Embedded
private Address billingAddress;
@Embedded
@AttributeOverrides({
@AttributeOverride(name = "street",
column = @Column(name = "shipping_street", length = 120)),
@AttributeOverride(name = "city",
column = @Column(name = "shipping_city", length = 60)),
@AttributeOverride(name = "postalCode",
column = @Column(name = "shipping_postal_code", length = 12))
})
private Address shippingAddress;
@Column(precision = 12, scale = 2)
private BigDecimal creditLimit;
private LocalDate registeredOn;
private Instant lastLoginAt;
protected Customer() {
}
public Customer(String name) {
this.name = name;
}
public Long getId() { return id; }
public String getName() { return name; }
public CustomerTier getTier() { return tier; }
public void setTier(CustomerTier tier) { this.tier = tier; }
public Address getBillingAddress() { return billingAddress; }
public void setBillingAddress(Address a) { this.billingAddress = a; }
public Address getShippingAddress() { return shippingAddress; }
public void setShippingAddress(Address a) { this.shippingAddress = a; }
}
enum CustomerTier { STANDARD, SILVER, GOLD }The customers table has one flat set of columns: id, name, tier, street, city, postal_code, shipping_street, shipping_city, shipping_postal_code, and so on. No join is involved.
Null embeddables
If every column of an embedded object is NULL, Hibernate loads the field as null, not as an Address with null fields. Code like customer.getBillingAddress().getCity() can then throw a NullPointerException even though you never stored a null address. Either check for null in the getter or make sure at least one column always has a value.
Querying through an embeddable
Derived queries follow the property path into the embedded object.
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface CustomerRepository extends JpaRepository<Customer, Long> {
List<Customer> findByBillingAddressCity(String city);
List<Customer> findByTier(CustomerTier tier);
}Enums
By default JPA stores an enum by its ordinal, the zero-based position in the declaration. STANDARD becomes 0, SILVER becomes 1, and GOLD becomes 2. This breaks data silently. If someone inserts BRONZE before SILVER, every stored 1 now means a different tier.
Use @Enumerated(EnumType.STRING) to store the constant's name instead.
| Mode | Stored value | Safe to reorder constants | Safe to rename constants |
|---|---|---|---|
| `ORDINAL` (default) | `0`, `1`, `2` | No | Yes |
| `STRING` | `"GOLD"` | Yes | No, existing rows need a migration |
Converters for custom types
Sometimes neither mode fits. You may want stable short codes in the database that differ from the Java names. An AttributeConverter translates between a Java type and a column value.
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;
public enum PaymentMethod {
CARD("C"), TRANSFER("T"), CASH("H");
private final String code;
PaymentMethod(String code) {
this.code = code;
}
public String getCode() {
return code;
}
public static PaymentMethod fromCode(String code) {
for (PaymentMethod m : values()) {
if (m.code.equals(code)) {
return m;
}
}
throw new IllegalArgumentException("Unknown payment code: " + code);
}
@Converter
public static class PaymentMethodConverter
implements AttributeConverter<PaymentMethod, String> {
@Override
public String convertToDatabaseColumn(PaymentMethod method) {
return method == null ? null : method.getCode();
}
@Override
public PaymentMethod convertToEntityAttribute(String code) {
return code == null ? null : PaymentMethod.fromCode(code);
}
}
}Apply it to a field with @Convert(converter = PaymentMethod.PaymentMethodConverter.class). Set @Converter(autoApply = true) to use it for every field of that type. Always handle null in both directions, because the framework passes nulls to the converter.
Converters have limits. Hibernate cannot translate a converted value inside every kind of query, so test any query that filters on a converted field. Also avoid converters on @Id and @Version fields.
Numbers, dates and text
Pick Java types that match how the data behaves:
- Use
BigDecimalfor money, withprecisionandscaleon@Column. Never usedouble, which cannot represent most decimal fractions exactly. - Use
LocalDatefor a calendar date,LocalDateTimefor a date and time with no zone, andInstantfor a moment on the timeline. PreferInstantfor timestamps like "last login". - Use
Stringwith an explicitlength. The default is 255 characters, and a longer value fails on insert in most databases. - Use
@Lobonly for truly large text or binary data. Many databases handle it in a slower, special way.
Collections of values
To store a list of simple values or embeddables without a separate entity, use @ElementCollection. It creates a child table with a foreign key to the owner, but the elements have no identity of their own. Hibernate may delete and reinsert all rows of the collection when you change it. Choose a real entity with @OneToMany when the elements need their own lifecycle or queries.
Exercise
A Ticket entity has @Enumerated with no arguments on a Priority enum declared as LOW, MEDIUM, HIGH. A developer later adds URGENT at the top of the list. What goes wrong, and what is the fix?
Show answer
The default mode is ORDINAL, so the database holds 0, 1 and 2. Adding URGENT first shifts every constant, so existing rows with 0 (formerly LOW) now read as URGENT, and so on. The fix is to declare @Enumerated(EnumType.STRING) and migrate the existing numeric values to the constant names. Adding new constants at the end would also have avoided the shift, but STRING removes the fragility entirely.
Exercise
Why does embedding Address twice in Customer without any extra annotations fail, and which annotation fixes it?
Show answer
Both embedded copies map their fields to the same column names (street, city, postal_code), which produces duplicate column mappings. @AttributeOverride (or @AttributeOverrides for several) on one of the fields renames its columns, for example to shipping_street.