Reputation: 3850
I am stuck in a tricky situation while writing a JPQL query, following are my tables:-
Order_
order_id quotation_id 1 11 2 12
Quotation
q_id qr_id 11 101 12 102
QRequest
qr_id name 101 Name 1 102 Name 2
@Entity
@Table(name = "Order_")
public class Order {
@Id
@GeneratedValue
private long id;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "q_id", unique = true)
private Quotation quotation;
}
@Entity
public class QRequest {
@Id
@GeneratedValue
private long id;
@Column(nullable = false)
private String name;
}
@Entity
public class Quotation {
@Id
@GeneratedValue
private long id;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "qr_id", nullable = false)
private QRequest qRequest;
}
public List<QRequest> getQRequestForOrders(List<Long> orderIds) {
String query = "Select qr from QRequest qr, Quotation q, Order o " +
"where o.quotation.qRequest.id = qr.id " +
"and o.id in (:orderIds) ";
TypedQuery<QRequest> typedQuery = entityManager.createQuery(query, QRequest.class);
typedQuery.setParameter("orderIds", orderIds);
return typedQuery.getResultList();
}
I am trying to get a List<QRequest>
from a List
of order_id
.
This is the SQL equivalent query:-
select qr.* from QRequest qr
inner join Quotation q on q.qr_id = qr.id
inner join Order_ o on o.quotation_id = q.id
where o.id in (1,2);
I am looking for a equivalent JPQL query.
Upvotes: 2
Views: 6117
Reputation: 4542
In this case it may be worth to set a bi-directional relationship to make it easier to query, like this for example:
@Entity
public class QRequest {
@Id
@GeneratedValue
private long id;
@Column(nullable = false)
private String name;
@OneToMany(mappedBy = "qRequest")
private Quotation quotation;
}
@Entity
public class Quotation {
@Id
@GeneratedValue
private long id;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "qr_id", nullable = false)
private QRequest qRequest;
}
"Select qr from QRequest qr " +
"join qr.quotation q "
if you want to avoid it you can instead
"Select qr from QRequest qr, Quotation q, Order o " +
"where o.quotation.qRequest.id = qr.id " +
"and o.quotation.id = q.id " +
"and o.id in (:ids) "
and .setParameter("ids", your_list);
In both cases the query will return a collection of QRequest
Upvotes: 3