Video in progress

What is an `AttributeConverter` and when do you use it?

AttributeConverter<X, Y> converts a Java type to a database column type and back. It's handy for value objects (money, phone number), enums with custom codes, or simple encryption. It doesn't apply to @Id, @Version or associations.

📖 Answer

For example, you need to store an enum in the database as a short code:

public enum Status {
    NEW("N"), PAID("P"), CANCELLED("C");
    final String code;
    Status(String code) { this.code = code; }
    static Status of(String c) {
        return Arrays.stream(values()).filter(s -> s.code.equals(c)).findFirst().orElseThrow();
    }
}

@Converter(autoApply = true)
public class StatusConverter implements AttributeConverter<Status, String> {
    public String convertToDatabaseColumn(Status s) { return s == null ? null : s.code; }
    public Status convertToEntityAttribute(String c) { return c == null ? null : Status.of(c); }
}

With autoApply = true it's applied to every field of type Status automatically; otherwise you write @Convert(converter = StatusConverter.class) on the field. Storing an enum by code is safer than ORDINAL and more compact than STRING: even if you rename the enum constant, the code in the database doesn't change.

Other typical cases: writing a Money or PhoneNumber value object into one column, or storing a Duration as seconds.

Things to watch:

  • the converter must handle null itself, which is why the checks above are there;
  • in JPQL the parameter goes through the converter too: for where o.status = :s you pass Status.PAID, not "P";
  • for mutable types (for example, List), dirty checking compares with equals, so use an immutable type;
  • for complex structures (JSON), Hibernate 6's @JdbcTypeCode(SqlTypes.JSON) is better.