On JavaEE environment, I use JPA 2.1 implementation with EclipseLink,
I have some entities that contain enums
. So I have created converters for these enumerations.
Car entity :
@Entity
public class Car implements Serializable {
private static final long serialVersionUID = 6L;
@Id
private String id;
@Convert (converter = CarColorConverter.class)
private CarColor color;
public enum CarColor {
Black,
Gray,
White,
Red
};
public Car () {
id = GenerateUUID.id ();
}
....
}
CarColor Converter :
@Converter (converterClass = CarColorConverter.class, name = "CarColorConverter")
public class CarColorConverter implements AttributeConverter<CarColor, String> {
private static final String BLACK = "Black";
private static final String GRAY = "Gray";
private static final String WHITE = "White";
private static final String RED = "Red";
@Override
public String convertToDatabaseColumn (CarColor entityData) {
switch (entityData) {
case Black:
return BLACK;
case Gray:
return GRAY;
case White:
return WHITE;
case Red:
return RED;
default:
throw new IllegalArgumentException ("Unknown : " + entityData);
}
}
@Override
public CarColor convertToEntityAttribute (String dbData) {
switch (dbData) {
case BLACK:
return CarColor.Black;
case GRAY:
return CarColor.Gray;
case WHITE:
return CarColor.White;
case RED:
return CarColor.Red;
default:
throw new IllegalArgumentException ("Unknown : " + dbData);
}
}
}
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence
version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="xyz-restful-api" transaction-type="RESOURCE_LOCAL">
<!-- Converters -->
<!--<class>com.xyz.model.converters.CarColorConverter</class>-->
<!-- Entities / Model -->
<class>com.xtz.model.Car</class>
<properties>
...
</properties>
</persistence-unit>
</persistence>
When I comment the declaration of the converter on the persistence.xml file, and try to persist my entities in the DB I get this error : "Please ensure the converter class name is correct and exists with the persistence unit definition.". and no compilation time exception, only a warning pretty explicit :
Class "com.xyz.model.converters.CarTypeConverter" is annotated, but not listed in the persistence.xml file
However, when I uncomment the declaration of the converter on the on the persistence.xml file, and try to persist my entities in the DB I get this error : "Please ensure the converter class name is correct and exists with the persistence unit definition.". and a compilation time exception :
Class "com.xyz.model.converters.CarColorConverter" is listed in the persistence.xml file, but is not annotated
Am I declaring the converters in a wrong way ?
Thank you.