【问题标题】:Using JPA AttributeConverter for Boolean Y/N field: "Unable to render boolean literal value"将 JPA AttributeConverter 用于布尔 Y/N 字段:“无法呈现布尔文字值”
【发布时间】:2016-09-20 23:29:16
【问题描述】:

我正在实施解决方案 here 以将“Y”/“N”列转换为布尔值:

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

.. 和:

@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);
    }
}

问题是我似乎无法在 JPQL 中使用布尔值。以下代码给出了以下错误:

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

错误:

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

【问题讨论】:

    标签: java jpa jpql


    【解决方案1】:

    原来,因为这个字段在转换之前是一个varchar/char,JPQL需要把它当作一个字符串来处理。我不确定是否有更好的方法可以做到这一点,但以下方法有效:

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

    【讨论】:

      猜你喜欢
      • 2021-08-18
      • 2021-12-14
      • 1970-01-01
      • 1970-01-01
      • 2011-08-28
      • 1970-01-01
      • 2023-01-03
      • 1970-01-01
      相关资源
      最近更新 更多