I have a field in my database that contains a “Y” if true and a null if false. I have represented it as Boolean in my entity because I want it to appear as a checkbox on my screens. I have modified datatypes.xml in my global module like this:
However, when I try to access a record with a “Y” in the field, I get this:
ConversionException:
Exception Description: The object [Y], of class [class java.lang.String],
from mapping [org.eclipse.persistence.mappings.DirectToFieldMapping[retcheck-->
gwtrans.RETCHECK]] with descriptor [RelationalDescriptor(com.paslists.prm.entity.GWTrans
--> [DatabaseTable(gwtrans)])], could not be converted to [class java.lang.Boolean].
I think I’ve resolved this by using the @Converter annotations. Here’s what I did for anyone else who needs it:
Create a new class in my entity area (com.paslists.prm.entity):
package com.paslists.prm.entity;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
/**
* Created by eraskin on 1/23/17.
*/
@Converter
public class BooleanTFConverter implements AttributeConverter<Boolean, String> {
@Override
public String convertToDatabaseColumn(Boolean value) {
if (Boolean.TRUE.equals(value)) {
return "Y";
} else {
return "";
}
}
@Override
public Boolean convertToEntityAttribute(String value) {
return "Y".equals(value) || "1".equals(value) || "T".equals(value);
}
}
This class will return a “Y” for true and an empty string for false. It will also treat a “Y”, a “T”, or a “1” as true (just as a precaution for dirty data).