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

Get the Edge with a Professional Java IDE. 30-day free trial.

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();

 

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.

Topics:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}