【发布时间】:2014-07-13 07:55:47
【问题描述】:
我已尝试通读 QueryDSL 文档,但我仍然很困惑。我习惯于编写大量 SQL,但这是我第一次真正尝试使用 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 是一个简单的实体,带有一个id 代表一个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 对象不是 Provider 的 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 方向而不是 QProvider.provider.contact 对象的一部分这一事实有关,但我真的不知道这应该如何完成。
我是否走在正确的轨道上?我什至不确定我的加入是否正确。
【问题讨论】: