Spring Jpa Projection 接口出现布尔类型错误

问题描述 投票:0回答:2

问。为什么 JPA Projection 无法将
Mysql bit(1)
转换为
Java Boolean

当 Mysql

Projection type must be an interface!

 类型映射到 Java 
bit(1)
 类型时,
Spring Jpa Projection 出现错误
Boolean

Jpa 将实体类中的布尔列转换为 Mysql 表中的 bit(1) 列。

如果我将 PlanInfoProjection 接口

getIsBasic
Integer
的类型更改为
Boolean
,则不起作用。为什么会出现错误?

JPA 存储库

@Query(nativeQuery=true, value="select true as isBasic from dual")
ProductOrderDto.PlanInfoProjection findPlanInfoById(Long id);

投影接口

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
    }
}
mysql spring spring-data-jpa boolean projection
2个回答
8
投票

这似乎不是开箱即用的。对我有用的(虽然我使用的是 DB2,所以我的数据类型不同,但这应该不是问题)是对其进行注释并使用 SpEL,如下所示:

    @Value("#{target.isBasic == 1}")
    boolean getIsBasic();

这只是获取你的 int 值(0 代表 false,1 代表 true)并返回一个布尔值。也应该与

Boolean
一起使用,但我没有测试它。

另一种选择是使用

@Value("#{T(Boolean).valueOf(target.isBasic)}")
但这仅适用于字符串值,因此您必须在数据库中存储“true”或“false”。使用 T(),您可以将静态类导入 Spring 表达式语言,然后只需调用返回布尔值的 valueOf 方法(
Boolean
boolean


0
投票

ch1ll 的解决方案不适用于我的情况。 有效的是字段和方法命名;

select flag from some_table;  // in this example flag is field with boolean type
Method name in interface projection - "boolean isFlag()"

没有 getFlag(),也没有 getIsFlag()。如果字段的名称是“isFlag”,则方法将是 boolean isIsFlag(),但我没有尝试。

© www.soinside.com 2019 - 2024. All rights reserved.