Using JPA AttributeConverter for Boolean Y/N field: “Unable to render boolean literal value”

£可爱£侵袭症+ 提交于 2020-01-02 07:45:32

问题


I'm implementing the solution here to convert a 'Y'/'N' column to a Boolean value:

@Basic(optional = false)
@Column(name = "ACTIVE_YN")
@Convert(converter = BooleanToStringConverter.class)
private Boolean active;

.. and:

@Converter
public class BooleanToStringConverter implements AttributeConverter<Boolean, String> {

    @Override
    public String convertToDatabaseColumn(Boolean value) {
        return (value != null && value) ? "Y" : "N";
    }

    @Override
    public Boolean convertToEntityAttribute(String value) {
        return "Y".equals(value);
    }
}

The problem is that I can't seem to use boolean values in JPQL. The following code gives the error below:

@Query("select thing from MyThing thing where thing.id = :id and thing.active = true")
public MyThing findOneActive(@Param("id") ThingIdEnum id);

Error:

java.lang.IllegalArgumentException: Validation failed for query for method public abstract x.y.z.MyThing x.y.z.MyThingRepository.findOneActive(x.y.z.ThingIdEnum)!
...
Unable to render boolean literal value [select thing from MyThing thing where thing.id = :id and thing.active = true]
...
org.hibernate.type.descriptor.converter.AttributeConverterTypeAdapter cannot be cast to org.hibernate.type.LiteralType

回答1:


Turns out, because this field is a varchar/char before conversion, the JPQL needs to treat it as a string. I'm not sure if there's a better way to do this but the following worked:

@Query("select thing from MyThing thing where thing.id = :id and thing.active = 'Y'")
public MyThing findOneActive(@Param("id") ThingIdEnum id);


来源:https://stackoverflow.com/questions/39581225/using-jpa-attributeconverter-for-boolean-y-n-field-unable-to-render-boolean-li

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!