JPQL内部联接查询

时间:2018-04-23 09:10:06

标签: java hibernate jpa jpql

我在编写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();
  }

我正试图从List<QRequest> List获得order_id。 这是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查询。

1 个答案:

答案 0 :(得分:2)

在这种情况下,可能需要设置双向关系以便于查询,例如:

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

在这两种情况下,查询都会返回QRequest

的集合