【问题标题】:Using hibernate 5, How to use CriteriaBuilder.literal(boolean) in my select expression?使用休眠 5,如何在我的选择表达式中使用 CriteriaBuilder.literal(boolean)?
【发布时间】:2016-08-30 05:54:47
【问题描述】:

这是我使用 JPA 标准 API 构建 Select 的方式

CriteriaQuery<MyDto> crit = builder.createQuery(MyDto.class).distinct(true);
Root<MyEntity> root = crit.from(MyEntity.class);

List<Expression<?>> listFields = new ArrayList<>();
listFields.add(root.get("intField"));
listFields.add(root.get("stringField"));
listFields.add(builder.<Boolean> selectCase().when(
        builder.isTrue(root.<Boolean> get("booleanField")), true).otherwise(false));
listFields.add(builder.literal(false));

Expression[] arraySelect = listFields.toArray(new Expression[listFields.size()]);
crit.multiselect(arraySelect);

我的 obj 有一个构造函数:

public MyDto(Long pIntAttr, String pStringAttr, boolean pBooleanAttr1, boolean pBooleanAttr2) {
    // Build my item
}

我使用的是 hibernate 4 并且在处理程序上有一个空指针,所以在查看网络后,看到 Hibernate 5 中现在有一个 BooleanValueHandler,我升级了。

现在我得到的错误是:

原因:org.hibernate.hql.internal.ast.QuerySyntaxException:无法在类 [mypackage.MyDto] 上找到适当的构造函数。预期的参数是:long, java.lang.String, boolean [select distinct new mypackage.MyDto(generatedAlias0.intField, generatedAlias0.stringField, case when generatedAlias1.booleanField = true then true else false end, false) from myEntityPackage.MyEntity as generatedAlias0 ]

如果我将literal(false) 替换为literal(0) 并在构造函数中将pBooleanAttr2 的类型更改为Integer,它可以正常工作。

如果我保留布尔值但将其从构造函数中删除,它会告诉我我的选择中有 4 个字段,而构造函数中只有 3 个。

那么我错过了什么?

当然我的查询比这更复杂。

编辑:现在我使用这个解决方法来获得一个可以在我的选择中使用的文字(布尔值):

protected Expression<Boolean> getLiteralBoolean(final boolean pBoolean) {
    return builder.<Boolean> selectCase().when(builder.and(), pBoolean).otherwise(pBoolean);
}

【问题讨论】:

    标签: hibernate jpa boolean criteria literals


    【解决方案1】:

    【讨论】:

      猜你喜欢
      • 2011-04-12
      • 2011-08-20
      • 1970-01-01
      • 2013-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-22
      • 2021-12-24
      相关资源
      最近更新 更多