hyn*_*iia 12 mysql spring boolean projection spring-data-jpa
Mysql bit(1)为Java Boolean?Projection type must be an interface!当Mysqlbit(1)类型映射到Java类型时, Spring Jpa Projection出现错误Boolean。
Jpa 将实体类中的布尔列转换为 Mysql 表中的位(1)列。
如果我将getIsBasicPlanInfoProjection 接口中的类型更改Integer为Boolean,则不起作用。为什么会出现错误呢?
@Query(nativeQuery=true, value="select true as isBasic from dual")
ProductOrderDto.PlanInfoProjection findPlanInfoById(Long id);
Run Code Online (Sandbox Code Playgroud)
public class ProductOrderDto {
@Getter
public static class PlanInfo {
private Boolean isBasic;
public PlanInfo(PlanInfoProjection projection) {
// this.isBasic = projection.getIsBasic(); //<-- I want to use like this.
if (projection.getIsBasic() == null) {
this.isBasic = null;
} else {
this.isBasic = projection.getIsBasic() == 0 ? false : true; // <-- I have to convert
}
}
}
public interface PlanInfoProjection {
Integer getIsBasic(); // It works, but I have to convert Integer to Boolean to use.
//Boolean getIsBasic(); // doesn't work, but why???
//Boolean isBasic(); // also doesn't work
//boolean isBasic(); // also doesn't work
}
}
Run Code Online (Sandbox Code Playgroud)
ch1*_*1ll 11
看起来这并不能开箱即用。对我有用的(虽然我使用的是 DB2,所以我的数据类型不同,但这应该不是问题)是对其进行注释并使用 SpEL,如下所示:
@Value("#{target.isBasic == 1}")
boolean getIsBasic();
Run Code Online (Sandbox Code Playgroud)
这只需要你的 int 值(0 代表 false,1 代表 true)并返回一个布尔值。也应该可以使用,Boolean但我没有测试它。
另一种选择是使用@Value("#{T(Boolean).valueOf(target.isBasic)}"),但这仅适用于字符串值,因此您必须在数据库中存储“true”或“false”。使用 T(),您可以将静态类导入 Spring 表达式语言,然后只需调用返回布尔值(或Boolean)boolean的valueOf 方法
| 归档时间: |
|
| 查看次数: |
3622 次 |
| 最近记录: |