Set String "Y" to mean Boolean true and null to mean Boolean false?

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:


    <datatype class="com.haulmont.chile.core.datatypes.impl.BooleanDatatype" trueString="Y" falseString=""/>

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].

What am I doing wrong?

I think I’ve resolved this by using the @Converter annotations. Here’s what I did for anyone else who needs it:

  1. 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).

  1. I then modified the field in my Entity like this:

@Column(name = "RETCHECK")
@Convert(converter=BooleanTFConverter.class)
protected Boolean retcheck;

This appears to work. Open to suggestions if there is a better way.

Thank you for sharing the solution. It’s currently the best possible way, and we are going to add it to the documentation.

I missed one step in the above solution:

  1. Edit persistence.xml in the global module to include the line:

<class>com.paslists.prm.entity.BooleanTFConverter</class>

The entire persistence.xml in my app looks like this:


<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             version="2.0">
    <persistence-unit name="prm"
                      transaction-type="RESOURCE_LOCAL">
        <class>com.paslists.prm.entity.GWTrans</class>
        <class>com.paslists.prm.entity.Gateway</class>
        <class>com.paslists.prm.entity.GWProds</class>
        <class>com.paslists.prm.entity.GWComment</class>
        <class>com.paslists.prm.entity.BooleanTFConverter</class>
    </persistence-unit>
</persistence>

Sorry for the oversight.