Converter in Java Persistence with Spring Data and Hibernate

Overview

In Java Persistence API (JPA), converters are a powerful feature used to transform data between the database and the Java application. They are particularly useful for handling custom data types that require specific processing when being persisted or retrieved. Converters implement the AttributeConverter interface, which allows for conversion between a Java type and a database type. This interface provides a standardized extension point in JPA for such transformations.

Implementing a Converter

To implement a converter, you need to create a class that implements the AttributeConverter interface. This interface requires two methods: convertToDatabaseColumn and convertToEntityAttribute. The class must also be annotated with @Converter.

Example: MonetaryAmountConverter

The MonetaryAmountConverter is an example of a converter that transforms a MonetaryAmount Java object into a String for database storage and vice versa. This is particularly useful when you want to store complex objects as simple database types like VARCHAR.

Listing 6.16 Converting between strings and MonetaryValue

@Converter
public class MonetaryAmountConverter
  implements AttributeConverter<MonetaryAmount, String> {

  @Override
  public String convertToDatabaseColumn(MonetaryAmount monetaryAmount) {
      return monetaryAmount.toString();
  }

  @Override
  public MonetaryAmount convertToEntityAttribute(String s) {
      return MonetaryAmount.fromString(s);
  }
}
  • convertToDatabaseColumn: Converts a MonetaryAmount entity type to a String for storage in the database.
  • convertToEntityAttribute: Converts a String from the database back to a MonetaryAmount entity type.

Example: ZipcodeConverter

The ZipcodeConverter is another example that handles different formats of ZIP codes, such as German and Swiss ZIP codes, by converting them to a String for database storage and back to the appropriate Java object.

Listing 6.18 The ZipcodeConverter class

@Converter
public class ZipcodeConverter
    implements AttributeConverter<Zipcode, String> {

    @Override
    public String convertToDatabaseColumn(Zipcode attribute) {
        return attribute.getValue();
    }

    @Override
    public Zipcode convertToEntityAttribute(String s) {
        if (s.length() == 5)
            return new GermanZipcode(s);
        else if (s.length() == 4)
            return new SwissZipcode(s);
        throw new IllegalArgumentException(
            "Unsupported zipcode in database: " + s
        );
    }
}
  • convertToDatabaseColumn: Converts a Zipcode object to a String.
  • convertToEntityAttribute: Determines the type of Zipcode based on the length of the String and creates either a GermanZipcode or SwissZipcode.

Applying Converters

Converters are applied to entity attributes using the @Convert annotation. This annotation specifies which converter to use for a particular attribute.

Example: Applying MonetaryAmountConverter

In the Item class, the MonetaryAmountConverter is applied to the buyNowPrice field, which is stored in the ITEM table as a VARCHAR column.

@NotNull
@Convert(converter = MonetaryAmountConverter.class)
@Column(name = "PRICE", length = 63)
private MonetaryAmount buyNowPrice;

Example: Applying ZipcodeConverter

In the User class, the ZipcodeConverter is applied to the zipcode attribute of the embedded homeAddress.

@Entity
@Table(name = "USERS")
public class User {
    @Convert(
        converter = ZipcodeConverter.class,
        attributeName = "city.zipcode"
    )
    private Address homeAddress;
    //  . . .
}

The attributeName uses a dot syntax to specify the path to the zipcode attribute within nested embeddable classes. This allows for precise application of the converter to specific attributes within complex object structures.