Converting values between object data model and relation data model in JPA 2 is super easy. Here are the steps:

1. Declare converter for value pair thet you want to be converted. Let’s say that we want to convert boolean values to integer, then we declare converter like this:

Converter has to implement javax.persistence.AttributeConverter<ObjectModelType, RelationalModelType>. This interface declared to methods with very clear names – at first sight one can tell what they are responsible for.

Instead of using annotation you can use XML descriptor of course.

2.a Declare Converter class to be applied automatically – just add autoApply attribute set to true to Converter annotation:

2. b If Converter is not applied automatically then annotate entity, mapped superclass or embeddable class attribute with javax.persistence. Convert annotation (or add appropriate XML element to XML descriptor).

converter attribute specifies Converter class to be used for conversion.

If you annotate attribute that is not a basic type or element collection of basic types than you must also add attributeName attribute to annotation to tell JPA to which attribute you want the converter to be applied to.

Convert annotation can also exclude or or overwrite default conversion, e.g. if we have defined some other converter like:

than this converter would not be applied to aforementioned locked field because other converter is specified directly on field.

In order to exclude this attribute from conversion Converter annotation must have disableConversion attribute specified with value true.

Some hints:

According to JPA 2.1 specification point 11.1.10 Convert Annotation some attributes should not be applied to some fields like id, Enumerated and Temporal (annotated) types, relationship attributes or version attributes.

Convert annotation can be applied to entity class that extends mapped superclass to overwrite conversion mapping, see point 11.1.10 Example 11: Override conversion mappings for attributes inherited from a mapped superclass.

When using converter in Java SE environment one needs to specify converter class in persistence.xml, same as with entity classes.

That’s it ! Have a nice day 🙂