简体   繁体   中英

JPQL inner join query

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM