具有非直接关系的Criteria API查询

时间:2016-10-24 14:02:23

标签: jpa

美好的一天!

SQL查询非常有效:

select oi.nameshort from creditrequest c
join users u on u.id=c.user_id
join peoplemanagers pm on pm.people_id=u.people_id

--  join organiztion o on pm.organization_id=o.id

join organizationinfo oi on oi.organization_id=pm.organization_id
where oi.nameshort like 'Hydro%'

当我尝试将SQL转换为JPA Criteria API时出现问题。我需要对表 organizationinfo 进行限制,但组织没有直接引用它。  我试试

pb.like(root.get(CreditRequestEntity_.userId)
.get(UsersEntity_.peopleId)
.get(PeopleEntity_.id)
.get(PeopleManagerEntity_.organizationId)
.get(OrganizationInfoEntity_.organizationId),
filter.getOrganization());

但它在 .get(PeopleEntity_.id)上失败。 如何解决Criteria API上的问题?

类:

@Entity
@Table(name = "creditrequest")
public class CreditRequestEntity { 
    ... 
    @ManyToOne
    @JoinColumn(name = "borrower_id")
    private BorrowerEntity borrower;
    ... 
}

@Entity
@Table(name = "borrower")
public class BorrowerEntity { 
    ... 
    @ManyToOne
    @JoinColumn(name = "organization_id")
    private OrganizationEntity organizationId; 
    ... 
}

@Entity
@Table(name = "organization")
public class OrganizationEntity { ... }

@Entity
@Table(name = "organizationinfo")
public class OrganizationInfoEntity  { ...
        @Column(name = "nameshort")
        private String nameShort;

        @ManyToOne
        @JoinColumn(name = "organization_id")
        private OrganizationEntity organizationId; 
    ... 
}

任何类都有字段ID作为主键。

1 个答案:

答案 0 :(得分:0)

if (filter.getOrganization() != null) {
    List<Expression<String>> expressions = new ArrayList<>();
    Subquery<OrganizationInfoEntity> psq = query.subquery(OrganizationInfoEntity.class);
    Root<OrganizationInfoEntity> orgInfoRoot = psq.from(OrganizationInfoEntity.class);
    psq.select(orgInfoRoot);

    Join<OrganizationEntity, OrganizationInfoEntity> borrowerOrganizationInfoJoin = root.join(CreditRequestEntity_.borrower)
    .join(BorrowerEntity_.organizationId).join(OrganizationEntity_.organizationInfo);

    PredicateBuilder pipb = new PredicateBuilder(builder);
    pb.add(builder.equal(borrowerOrganizationInfoJoin.get(OrganizationInfoEntity_.isActive), ActiveStatus.ACTIVE));
    expressions.add(borrowerOrganizationInfoJoin.get(OrganizationInfoEntity_.nameShort));
    pipb.like(filter.getOrganization(), expressions.toArray(new Expression[]{}));
    psq.where(pipb.getWherePredicates());

    pb.add(builder.exists(psq));
}