Close

Entity Attribute Converter

[Updated: Feb 28, 2018, Created: Feb 28, 2018]

The attribute converters allow us to convert the type of the entity attributes into/from a suitable type which can be persisted in database.

An attribute converter class must implement the javax.persistence.AttributeConverter interface and must be annotated with javax.persistence.Converter annotation.

An attribute whose type is desired to be converted can use javax.persistence.Convert annotation.

Example

@Entity
public class Report {
  @Id
  @GeneratedValue
  private long id;
  private String description;
  @Convert(converter = FileConverter.class)
  private File file;
    .............
}
@Converter
public class FileConverter implements AttributeConverter<File, String> {

  @Override
  public String convertToDatabaseColumn(File attribute) {
      return attribute.getAbsolutePath();
  }

  @Override
  public File convertToEntityAttribute(String dbData) {
      return new File(dbData);
  }
}

The main class

public class ExampleMain {
  private static EntityManagerFactory entityManagerFactory =
          Persistence.createEntityManagerFactory("example-unit");

  public static void main(String[] args) {
      try {
          nativeQuery("Show Columns from Report");
          persistEntity();
          nativeQuery("Select * from Report");
          findEntity();
      } finally {
          entityManagerFactory.close();
      }
  }

  private static void findEntity() {
      EntityManager em = entityManagerFactory.createEntityManager();
      Report report = em.find(Report.class, 1L);
      System.out.println("Report loaded: " + report);
      em.close();
  }


  public static void persistEntity() {
      Report report = new Report();
      report.setDescription("test report");
      report.setFile(new File("c:/temp/report-details.txt"));
      System.out.println("Persisting report: " + report);
      EntityManager em = entityManagerFactory.createEntityManager();
      em.getTransaction().begin();
      em.persist(report);
      em.getTransaction().commit();
      em.close();
  }

  public static void nativeQuery(String s) {
      EntityManager em = entityManagerFactory.createEntityManager();
      System.out.printf("'%s'%n", s);
      Query query = em.createNativeQuery(s);
      List list = query.getResultList();
      for (Object o : list) {
          if (o instanceof Object[]) {
              System.out.println(Arrays.toString((Object[]) o));
          } else {
              System.out.println(o);
          }
      }
      em.close();
  }
}
'Show Columns from Report'
[ID, BIGINT(19), NO, PRI, NULL]
[DESCRIPTION, VARCHAR(255), YES, , NULL]
[FILE, VARCHAR(255), YES, , NULL]
Persisting report: Report{id=0, description='test report', file=c:\temp\report-details.txt}
'Select * from Report'
[1, test report, c:\temp\report-details.txt]
Report loaded: Report{id=1, description='test report', file=c:\temp\report-details.txt}

Also check out H2 Database show statements tutorial.

Without @Converter

In above example, if we don't use our converter on File attribute then File instance will be persisted as a binary form.

@Entity
public class Report {
  @Id
  @GeneratedValue
  private long id;
  private String description;
  //@Convert(converter = FileConverter.class)
  private File file;
    .............
}
public class ExampleMain {
  private static EntityManagerFactory entityManagerFactory =
          Persistence.createEntityManagerFactory("example-unit");

  public static void main(String[] args) {
      try {
          nativeQuery("Show Columns from Report");
          persistEntity();
          nativeQuery("Select * from Report");
          findEntity();
      } finally {
          entityManagerFactory.close();
      }
  }
    .............
}
'Show Columns from Report'
[ID, BIGINT(19), NO, PRI, NULL]
[DESCRIPTION, VARCHAR(255), YES, , NULL]
[FILE, VARBINARY(255), YES, , NULL]
Persisting report: Report{id=0, description='test report', file=c:\temp\report-details.txt}
'Select * from Report'
[1, test report, [B@18518ccf]
Report loaded: Report{id=1, description='test report', file=c:\temp\report-details.txt}

All Serializable types which are not Java Basic types (String, primitives etc) can be persisted into VARBINARY SQL type, check out this tutorial for details.

Note

Converters can be used to convert basic attributes defined by entity classes, mapped superclasses, or embeddable classes. They cannot be used on the @Id, @Version, relationships (@OneToOne, @OneToMany, @ManyToOne ), @Temporal and @Enumerated attributes.

Example Project

Dependencies and Technologies Used:

  • h2 1.4.196: H2 Database Engine.
  • hibernate-core 5.2.12.Final: The core O/RM functionality as provided by Hibernate.
    Implements javax.persistence:javax.persistence-api version 2.1
  • JDK 1.8
  • Maven 3.3.9

Type Conversion of Entity Attribute Example Select All Download
  • jpa-converter-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • FileConverter.java
          • resources
            • META-INF

    See Also