Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Using "annotation only" conversion for Enumeration

DZone's Guide to

Using "annotation only" conversion for Enumeration

· Java Zone
Free Resource

Learn how to troubleshoot and diagnose some of the most common performance issues in Java today. Brought to you in partnership with AppDynamics.

Persisting Enum values using JPA is quite immediate; you can choose to put into the database:

  • the ordinal number (the default behavior); is the same of using @Enumerated( EnumType.ORDINAL) annotation for a given property;
  • the string rappresentation, annotating the property with @Enumerated(EnumType.STRING).

But what if you need to persist customized strings?

Say you need to persist an entity class named Car. The Car entity has an attribute, the color of the paint, that is defined by the enumeration PaintingEnum class below:

package org.enumDemo;
public enum PaintingEnum {RED, YELLOW, BLUE, WHITE}

You need to persist the painting enumeration attribute as follows:

  • for a painting color = PaintingEnum.WHITE you need to persist the string "Milky drops";
  • For a painting color = PaintingEnum.BLUE you need to persist the string "Deep sea";
  • and so on...

To achieve this, you can annotate the painting property as follow:

@ObjectTypeConverter(
name = "PaintingInnerConverter",
dataType = java.lang.String.class,
objectType = org.enumDemo.PaintingEnum.class,
conversionValues = {
@ConversionValue(dataValue = "Sun rays", objectValue = "YELLOW"),
@ConversionValue(dataValue = "Milky drops", objectValue = "WHITE"),
@ConversionValue(dataValue = "Passion color", objectValue = "RED"),
@ConversionValue(dataValue = "Deep sea", objectValue = "BLUE")
})

@Convert("PaintingInnerConverter")
protected PaintingEnum painting = PaintingEnum.WHITE; //default value for painting

public PaintingEnum getPainting(){
return painting;
}

public void setPainting(PaintingEnum painting) {
this.painting = painting;
}

This way you will be also able to retrieve data from the database using this kind of query:

Query query = em.createQuery( "select c from Car c where c.painting = org.enumDemo.PaintingEnum.WHITE" );
List whiteCarsList = query.getResultList();

 

Understand the needs and benefits around implementing the right monitoring solution for a growing containerized market. Brought to you in partnership with AppDynamics.

Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}