问题描述
使用查询DSL 和休眠(Spring Data JPA)来构建类似的查询
Using Query DSL with hibernate (Spring Data JPA) to build a query like so
if( bankId != null ){
query.where(
coopMember.personId.bankAccountId.isNotNull().and(
coopMember.personId.bankAccountId.bankBranch.bankId.eq(bankId))
);
}
return query.fetch();
这里的逻辑很简单:如果存在与某人相关联的银行帐户,请按银行ID过滤结果.
The logic here is simple: if there is a bank account associated with a person, filter the results by bank id.
BankAccount
实体具有一个 BankBranch
,其中包含 bankId
整数值. CoopMember
实体可能具有或不具有 BankAccount
The BankAccount
entity has a BankBranch
which holds bankId
integer value. A CoopMember
entity may or may not have a BankAccount
问题是执行上述QueryDSL查询时,即使存在非null检查,也会引发 NullPointerException
.
Problem is when the above QueryDSL query is executed, a NullPointerException
is thrown, even if a not null check is in place.
在将逻辑更改为跟随时,会引发相同的错误.我想知道为什么 bankBranch
不能被空检查":
On changing the logic to following the same error is thrown. I wonder why bankBranch
cannot be "null-checked":
if( bankId != null ){
query.where(
coopMember.personId.bankAccountId.isNotNull().and(
coopMember.personId.bankAccountId.bankBranch.isNotNull())
);
}
以下引发的堆栈跟踪:
推荐答案
在 coopMember.personId.bankAccountId.bankBranch
中使用调试器 bankBranch
为null,这在当时没有意义全部,因为所有 bankAccount
必须与 bankBranch
相关联.
Using debugger bankBranch
in coopMember.personId.bankAccountId.bankBranch
is null which is not making sense at all, as all bankAccount
s must have bankBranch
associated with it.
对我有用的是对查询小写内容进行不同的编写.左键连接 coopMember.personId.bankAccountId
上的 bankAccount
,然后像这样执行where子句
What worked for me is writing the query alittle bit differently.Left join bankAccount
on coopMember.personId.bankAccountId
then do where clause like so
JPAQuery<Integer> query = queryFactory.query()
.select(coopMember.memberId)
.distinct()
.from(coopMember)
.leftJoin(coopMember.personId.bankAccountId, bankAccount)
.where(coopMember.voided.isFalse());
if( bankId != null ){
query.where(
bankAccount.isNotNull().and(bankAccount.bankBranch.bankId.eq(bankId))
);
}
执行此操作使我能够访问 bankBranch
而不会抛出 NullPointerException
(尽管我仍然不明白为什么像这样直接访问 bankBranch
这个问题是不可能的.)
Doing this enabled me to access bankBranch
without throwing NullPointerException
(though still i don't understand why accessing bankBranch
directly like what is in the question is not possible).
这篇关于QueryDSL where子句上的NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!