1

In my Hibernate entity class I have a Boolean that I want to be true for certain characters in a column of VARCHAR2(1). But my code causes a SQLException: Fail to convert to internal representation. Can someone see what I'm doing wrong? My code is as follows:

In my entity I have:

...

    private Boolean flag;

    @Column(length = 1, name = "FLAG")
    @Convert(converter = FlagToBooleanConverter.class)
    public Boolean getFlag()
    {
        return flag;
    }

    void setFlag(Boolean flag)
    {
        this.flag = flag;
    }

...

@Converter
class FlagToBooleanConverter implements AttributeConverter<Boolean, String>
{
    @Override
    public Boolean convertToEntityAttribute(String value)
    {
        return (value.equals("X") || value.equals("Y"));
    }

    @Override
    public Boolean convertToDatabaseColumn(String value)
    {
        // My class should only read from the DB so I don't need this but I have to override it
        return null;
    }
}

UPDATE: Feels kind of hacky, but at the moment, to get the job down I've been using:

    private String flag;

    @Column(length = 1, name = "FLAG")
    String getFlag()
    {
        return flag;
    }

    void setFlag(String flag)
    {
        this.flag = flag;
    }

    @Transient
    public Boolean isFlag()
    {
        return (value.equals("X") || value.equals("Y"));
    }
MiketheCalamity
  • 1,229
  • 1
  • 15
  • 32
  • 2
    You should be using `value.equals("X") || ...` instead of `==`. The `convertToEntityAttribute` method will always return `false` as its coded now. – schtever Aug 31 '15 at 22:27
  • See this question: http://stackoverflow.com/questions/4287694/how-to-compare-different-language-string-values-in-java – aryn.galadar Aug 31 '15 at 22:50
  • Thanks, still doesn't fix the prevailing problem but that probably saves me a headache down the line. – MiketheCalamity Aug 31 '15 at 22:50
  • What if the value is `null`? `"X".equals(value) || "Y".equals(value)` will deal with that case. And if you create the DDL with Hibernate I would guess that you will have to define the column type with `@Column(name="FLAG", columnDefinition="VARCHAR(1)")` – Tobias Liefke Sep 01 '15 at 08:10
  • Why are you sure that you can simply return `null` from the `convertToDatabaseColumn` method? – Dragan Bozanovic Sep 01 '15 at 10:06
  • No, but I get the same error if I don't return null. – MiketheCalamity Sep 01 '15 at 14:22

0 Answers0