JPA Attribute Converter: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
 
(2 intermediate revisions by the same user not shown)
Line 13: Line 13:
An attribute converter allows the developer to specify methods to convert between the database and the Java representation of an attribute. Attribute conversion was introduced in JPA 2.1. All entity class. mapped superclass or embeddable class attributes can be type-converted, with the following exceptions:
An attribute converter allows the developer to specify methods to convert between the database and the Java representation of an attribute. Attribute conversion was introduced in JPA 2.1. All entity class. mapped superclass or embeddable class attributes can be type-converted, with the following exceptions:
* identity ([[@Id]]) attributes
* identity ([[@Id]]) attributes
* version attributes
* version ([[@Version]]) attributes
* relationship attributes
* relationship attributes ([[@OneToOne]], [[@OneToMany]], [[@ManyToOne]], [[@ManyToMany]])
* attributes annotated as [[@Temporal]] or [[@Enumerated]].
* attributes annotated as [[@Temporal]] or [[@Enumerated]].



Latest revision as of 06:46, 1 November 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. Attribute conversion was introduced in JPA 2.1. All entity class. mapped superclass or embeddable class attributes can be type-converted, with the following exceptions:

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 Payload payload;

The Converter Class

https://docs.oracle.com/javaee/7/api/javax/persistence/AttributeConverter.html

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<Payload, String> {

  @Override
  public String convertToDatabaseColumn(Payload attribute) {
     ...
  }

  @Override
  public Payload convertToEntityAttribute(String dbData) {
     ...
  }
}