jpa条件查询

piv4azn7  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(392)

我正在用selectcase编写jpa条件查询

CriteriaQuery<Tuple> query = builder.createTupleQuery();
Root<MyEntity> root = query.from(MyEntity.class);
Join document = ...
Join topic = ...

query.multiselect
(
        root.get("id"),
        document.get("id");
        builder.selectCase().when(builder.notEqual(document.get("id"), null), topic.get("id")),
        builder.selectCase().when(builder.notEqual(document.get("id"), null), topic.get("name")),
);
TypedQuery<Tuple> typedQuery = entityManager.createQuery(query);

如果我不应用2个select案例,查询就可以正常工作。
但在上面的代码中,我得到了空指针异常 entityManager.createQuery(query) .
我对select cases的意图是在文档的id不为null时打印主题的id和名称。 Exception :

java.lang.NullPointerException
    at org.hibernate.query.criteria.internal.predicate.ComparisonPredicate.render(ComparisonPredicate.java:172)
    at org.hibernate.query.criteria.internal.predicate.AbstractSimplePredicate.render(AbstractSimplePredicate.java:48)
    at org.hibernate.query.criteria.internal.Renderable.renderProjection(Renderable.java:34)

请说明我遗漏了什么。
编辑:我也尝试过:

builder.selectCase().when(builder.isNotNull(document), topic.get("id")),
    builder.selectCase().when(builder.isNotNull(document), topic.get("name"))
zzzyeukh

zzzyeukh1#

尝试添加其他选项:

builder.selectCase()
    .when(builder.isNotNull(document), topic.get("id"))
    .otherwhise(builder.literal("")), // assuming String is the type returned for the query
builder.selectCase()
    .when(builder.isNotNull(document), topic.get("name"))
    .otherwhise(builder.nullLiteral(String.class))    // assuming String is the type returned for the query

相关问题