JPQL 内连接查询

JPQL inner join query

我在编写 JPQL 查询时遇到了棘手的情况,以下是我的表:-

订单_

order_id     quotation_id

1            11

2            12

报价单

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();
  }

我正在尝试从 order_idList 中获取 List<QRequest>。 这是 SQL 等效查询:-

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);

我正在寻找等效的 JPQL 查询。

在这种情况下,可能值得设置双向关系以使其更易于查询,例如:

@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 "

如果你想避免它,你可以改为

"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) "

.setParameter("ids", your_list);

在这两种情况下,查询都将 return QRequest

的集合