Cmobilecom JPA 2.2.2 Developer Guide

11 Converter

Attribute converters are used to convert data between attribute basic types and column types. For example, map PhoneNumber class to a string column.
public class PhoneNumber {
	private String countryCode;
	private String areaCode;
	private String localNumber;
	
	public PhoneNumber(String countryCode, String areaCode, String localNumber) {
		this.countryCode = countryCode;
		this.areaCode = areaCode;
		this.localNumber = localNumber;
	}
	
	// getters and setters	
}
Converter:
@Converter(autoApply = true)
public class PhoneNumberConverter implements AttributeConverter<PhoneNumber, String> {

	@Override
	public String convertToDatabaseColumn(PhoneNumber attribute) {
		return attribute.getCountryCode() + "-" + attribute.getAreaCode() + "-" +
				attribute.getLocalNumber();
	}

	@Override
	public PhoneNumber convertToEntityAttribute(String dbData) {
		int index = dbData.indexOf('-');
		int index2 = dbData.indexOf('-', index+1);

		String countryCode = dbData.substring(0, index);
		String areaCode = dbData.substring(index+1, index2);
		String localNumber = dbData.substring(index2+1);
		return new PhoneNumber(countryCode, areaCode, localNumber);
	}
}
If autoApply is false, the converter needs to be explicitly specified for an attribute. For example,
public class Employee {

	@Column(length = 15)
	@convert(PhoneNumberConverter.class)
	private PhoneNumber phoneNumber;
}
Criteria APIInheritanceFrames / No Frames