QueryDSL/JPQL:如何建立联接查询? [英] QueryDSL / JPQL : how to build a join query?
问题描述
我试图阅读QueryDSL文档,但我仍然很困惑.我习惯于编写很多SQL,但这是我第一次真正使用QueryDSL w/JPQL(JPA2)时遇到的困难.
I've tried to read through the QueryDSL docs but I am still very confused. I'm accustomed to writing a lot of SQL, but this is my first real crack at using QueryDSL w/ JPQL (JPA2).
我有以下实体:
@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是一个简单实体,其中pk的id
.
where Contact is a simple entity with an id
for a pk.
@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;
}
我正在尝试编写一个查询,该查询在给定特定的Contact.id和Provider.id的情况下返回Contact
对象.如果Contact对象不是提供者的Contact集合的一部分,那么我正在寻找一个空值.
I'm trying to write a query which returns a Contact
object given a specific Contact.id and Provider.id. If the Contact object is not a part of the Provider's Contact collection, I'm looking for a null value.
我尝试了以下操作:
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方向而不是QProvider.provider.contact对象的一部分有关,但是我真的很茫然,无法确定应该如何处理完成.
I'm presuming it has something to do with the fact that my predicate references QContact.contact direction and not part of the QProvider.provider.contact object, but I'm really at a loss as to figure out how this should be done.
我甚至在正确的轨道上吗?我什至也不确定我的加入是否正确.
Am I even on the right track? I'm not even sure my join is correct either.
推荐答案
这应该有效
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/JPQL:如何建立联接查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!