QueryDsl - OR语句不起作用

时间:2013-11-23 02:53:59

标签: spring-data-jpa querydsl

我有以下QueryDSL查询:

    QCustomer customer = QCustomer.customer;

    BooleanBuilder builder = new BooleanBuilder();
    builder.or(customer.person.name.containsIgnoreCase(query));
    builder.or(customer.company.name.containsIgnoreCase(query));

    return builder;

我希望从包含name = query和/或包含查询参数的公司的人员那里获得结果。但我一无所获。

这是我的Customer类映射:

@OneToOne(orphanRemoval = false, optional = true, cascade = CascadeType.ALL)
private Company company;

@OneToOne(orphanRemoval = false, optional = true, cascade = CascadeType.ALL)
private Person person;

有人知道我在这里缺少什么吗?

我希望得到这样的查询:

select o 
from Customer 
where o.person.name like '%:name%' or o.company.name like '%:name%'

这是生成的查询:

select 
    count(customer0_.uid) as col_0_0_ 
from 
    Customer customer0_ 
cross join 
    Person person1_ 
cross join 
    Company company2_ 
where 
    customer0_.person_uid=person1_.uid 
    and customer0_.company_uid = company2_.uid 
    and (lower(person1_.name) like ? escape '!' or lower(company2_.name) like ? escape '!') limit ?

它使用计数,因为它是Spring Data用于对结果进行分页的第一个查询。

1 个答案:

答案 0 :(得分:3)

查询看起来不错。很可能你得到错误的结果,因为基于隐式属性的连接使连接成为内连接。

使用左连接可能会得到您需要的结果。

QPerson person = QPerson.person;
QCompany company = QCompany.company;
BooleanBuilder builder = new BooleanBuilder();
builder.or(person.name.containsIgnoreCase(str));
builder.or(company.name.containsIgnoreCase(str));

query.from(customer)
     .leftJoin(customer.person, person)
     .leftJoin(customer.company, company)
     .where(builder);