2016-09-19 49 views
3

我實施這一方案here到「Y」 /「N」列轉換爲布爾值:使用JPA AttributeConverter布爾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 

回答

3

事實證明,因爲這個領域是一個varchar /焦炭轉化前,JPQL需要把它作爲一個字符串。我不確定是否有更好的方法來做到這一點,但以下工作:

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