本文介绍了将JPA AttributeConverter用于布尔值Y / N字段:“无法呈现布尔文字值”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在实施解决方案,将'Y'/'N'列转换为布尔值:

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;

..和:

@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中的布尔值。下面的代码给出了以下错误:

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

错误:

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


推荐答案

事实证明,因为此字段在转换之前是varchar / char,所以JPQL需要将其视为字符串。我不确定是否有更好的方法可以做到这一点,但以下工作:

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

这篇关于将JPA AttributeConverter用于布尔值Y / N字段:“无法呈现布尔文字值”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 20:59