Jpa QueryDSL/JPQL:如何构建连接查询?
我试图通读QueryDSL文档,但我仍然很困惑。我习惯于编写大量SQL,但这是我第一次真正尝试使用QueryDSL w/JPQL(JPA2) 我拥有以下实体:Jpa QueryDSL/JPQL:如何构建连接查询?,jpa,jpql,querydsl,Jpa,Jpql,Querydsl,我试图通读QueryDSL文档,但我仍然很困惑。我习惯于编写大量SQL,但这是我第一次真正尝试使用QueryDSL w/JPQL(JPA2) 我拥有以下实体: @Entity public class Provider implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private Long id; @Ve
@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;
}
我正在尝试编写一个查询,返回给定特定Contact.id和Provider.id的Contact
对象。如果Contact对象不是提供者的Contact集合的一部分,我将查找空值
我尝试了以下方法:
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);
}
但我得到了以下错误:
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)
我认为这与我的谓词引用QContact.contact direction而不是QProvider.provider.contact对象的一部分有关,但我真的不知道该如何做
我走对了吗?我甚至不确定我的加入是否正确。这应该行得通
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);
}
很好用,谢谢。我没有意识到别名对QueryDSL如此重要。
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);
}