JPA Attribute Converter: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 19: Line 19:


==@Convert Annotation==
==@Convert Annotation==
Annotate the entity fields to be converter with @javax.persistence.Convert:


<syntaxhighlight lang='java'>
<syntaxhighlight lang='java'>
Line 26: Line 28:


==The Converter Class==
==The Converter Class==
Provide a converter class, which must implement AttributeConverter<''Entity-Field-Type'', ''Database-Type''> and be annotated with @javax.persistence.Converter:


<syntaxhighlight lang='java'>
<syntaxhighlight lang='java'>
@Converter
public class PayloadConverter implements AttributeConverter<String, String> {
    @Override
    public String convertToDatabaseColumn(String attribute) {
      return swapLetters(attribute);
    }
    @Override
    public String convertToEntityAttribute(String dbData) {
      return swapLetters(attribute);
    }
    private String swapLetters(String s) {
      ...
  }
}
</syntaxhighlight>
</syntaxhighlight>

Revision as of 20:23, 31 October 2018

External

Internal

Overview

An attribute converter allows the developer to specify methods to convert between the database and the Java representation of an attribute.

Playground Example

https://github.com/ovidiuf/playground/tree/master/spring/jpa/attribute-converter

Programming Model

@Convert Annotation

Annotate the entity fields to be converter with @javax.persistence.Convert:

@Convert(converter = PayloadConverter.class)
private String payload;

The Converter Class

Provide a converter class, which must implement AttributeConverter<Entity-Field-Type, Database-Type> and be annotated with @javax.persistence.Converter:

@Converter
public class PayloadConverter implements AttributeConverter<String, String> {

    @Override
    public String convertToDatabaseColumn(String attribute) {
       return swapLetters(attribute);
    }

    @Override
    public String convertToEntityAttribute(String dbData) {
       return swapLetters(attribute);
    }

    private String swapLetters(String s) {
      ...
   }
}