使用多个ManyToOne连接进行查询

时间:2015-06-29 20:32:02

标签: java hibernate querydsl

我有一个包含以下类的模型:

public class Organization  {

    private Person person;

}

public class PersonAddress  {

    private Person person;
    private Address address;

}

public class Address {

    ...

}

Person和Address之间没有直接关联,Person和PersonAddress之间也没有直接关联,也没有Address和PersonAddress。 PersonAddress是Person和Address之间的ManyToMany关联,但是我们试图避免映射相应的集合,因为它们的滥用可能会导致一些性能问题。

我正在尝试创建一个querydsl方法,将组织作为参数传递,并使用组织,人员和地址数据获取预测结果,但到目前为止,我最好的尝试是给我一个带有交叉连接的查询。

我可以以避免交叉连接的方式构建此查询吗?并且还避免创建集合关联。

这是querydsl查询和生成的SQL:

QueryDSL:

QOrganization organization = QOrganization.organization;
QPerson person = QPerson.person;
QPerson personOrganization = new QPerson("personOrganization");
QAddressPerson addressPerson = QAddressPerson.addressPerson;
QAddress address = QAddress.address;
QCity city = QCity.city;
JPQLQuery<Organization> query = newQuery().from(addressPerson,organization)
    .join(organization.person, person)//
    .join(addressPerson.address, address)//
    .join(address.city, city)//
    .leftJoin(addressPerson.person, personOrganization);
    BooleanBuilder builder = new BooleanBuilder();
    builder.and(organization.eq(organizationParam));
    query.where(builder)//
        .select(create(organization.id, organization.type, //
            QPerson.create(person.id, person.type, //
            QAddressPerson.create(addressPerson.id, //
            QAddress.create(address.id, //
            QCity.create(city.id, city.name), address.zipcode)))));

结果SQL:

select
    organization1_.org_id as col_0_0_,
    organization1_.org_tp as col_1_0_,
    person2_.pes_id as col_4_0_,
    person2_.pes_tp as col_5_0_,
    addresspe0_.enp_id as col_10_0_,
    address3_.end_id as col_11_0_,
    city4_.cid_id as col_12_0_,
    city4_.cid_nm as col_13_0_,
    address3_.END_VR_CEP as col_15_0_
from
    address_person addresspe0_ 
inner join
    address address3_ 
        on addresspe0_.end_id=address3_.end_id 
inner join
    city city4_ 
        on address3_.cid_id=city4_.cid_id 
left outer join
    person person5_ 
        on addresspe0_.pes_id=person5_.pes_id cross 
join
    organization organization1_ 
inner join
    person person2_ 
        on organization1_.pes_id=person2_.pes_id 
where
    and organization1_.org_id=?

1 个答案:

答案 0 :(得分:0)

此部分导致交叉连接

newQuery().from(addressPerson,organization)

您需要将addressPersonorganization移至内部或左侧联接。