QueryDSL/JPQL:如何构建连接查询?

Eri*_* B. 11 jpa jpql querydsl

我试过阅读QueryDSL文档,但我仍然很困惑.我习惯于编写很多SQL,但这是我第一次使用带有JPQL(JPA2)的QueryDSL.

我有以下实体:

@Entity
public class Provider implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Long id;

    @Version
    @Column(name = "version")
    private Integer version;


    private String name;

    @ManyToMany(cascade=CascadeType.ALL)
    @JoinTable(name = "provider_contact", joinColumns = @JoinColumn(name = "contact_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "provider_id", referencedColumnName = "id"))
    @OrderColumn
    private Collection<Contact> contact;
}
Run Code Online (Sandbox Code Playgroud)

其中Contact是一个带有idpk 的简单实体.

@Entity
public class Contact {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Long id;

    /**
     * User first name
     */
    @NotNull
    private String firstName;

    /**
     * User last name
     */
    @NotNull
    private String lastName;
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试编写一个查询,该查询返回Contact给定特定Contact.id和Provider.id 的对象.如果Contact对象不是Provider的Contact集合的一部分,我正在寻找一个null值.

我尝试过以下方法:

public Contact getContact( long providerId, long contactId ){
    Predicate p = QProvider.provider.id.eq(providerId).and(QContact.contact.id.eq(contactId));
    JPQLQuery query = new JPAQuery(em);
    return query.from(QProvider.provider).innerJoin(QProvider.provider.contact).where(p).singleResult(QContact.contact);
}
Run Code Online (Sandbox Code Playgroud)

但我收到以下错误:

Caused by: java.lang.IllegalArgumentException: Undeclared path 'contact'. Add this path as a source to the query to be able to reference it.
    at com.mysema.query.types.ValidatingVisitor.visit(ValidatingVisitor.java:78)
    at com.mysema.query.types.ValidatingVisitor.visit(ValidatingVisitor.java:30)
    at com.mysema.query.types.PathImpl.accept(PathImpl.java:94)
Run Code Online (Sandbox Code Playgroud)

我假设它与我的谓词引用QContact.contact方向而不是QProvider.provider.contact对象的一部分这一事实有关,但我真的不知道应该如何做到这一点.

我是否走在正确的轨道上?我甚至不确定我的加入也是正确的.

Tim*_*per 18

这应该工作

public Contact getContact(long providerId, long contactId) {
    QProvider provider = QProvider.provider;
    QContact contact = QContact.contact;
    return new JPAQuery(em).from(provider)
        .innerJoin(provider.contact, contact)
        .where(provider.id.eq(providerId), contact.id.eq(contactId))
        .singleResult(contact);
}
Run Code Online (Sandbox Code Playgroud)