问题
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