【问题标题】:JPQL inner join queryJPQL 内连接查询
【发布时间】:2018-04-23 09:10:05
【问题描述】:

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

订单_

order_id 报价单编号 1 11 2 12

报价

q_id qr_id 11 101 12 102

QRequest

qr_id 名称 101 姓名 1 102 名字 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&lt;QRequest&gt;。 这是 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 查询。

【问题讨论】:

  • 尝试:选择 qr.* FROM QReuqest qr INNER JOIN qr.Quotation q INNER JOIN q.Order_ o WHERE o.id IN (1,2)。如果不需要,不建议返回所有字段。如果需要混合一些表,则需要一个新类来映射它。
  • 请在询问 jpa 或 orm 时添加相关实体,因为它有很大帮助
  • @Zeromus 请检查更新后的问题。

标签: java hibernate jpa jpql


【解决方案1】:

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

@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 的集合

【讨论】:

  • 感谢您的回答。我正在寻找 o.id = 1 的所有 qr
  • 我测试了这个查询,它返回的结果集比预期的要大,你确定这个查询是我在问题中给出的 SQL 查询的 JPQL 等效项吗?
  • 你的意思是它返回的行太多或者它不是 QRequest 的集合?在您使用该查询的地方添加代码,也许那里有问题
  • 我添加了我正在调用的方法来运行查询。请检查。
  • mmh 我看不出有什么问题......所以它只是在运行时失败并出现强制转换异常?
猜你喜欢
  • 2014-02-21
  • 1970-01-01
  • 2021-02-15
  • 2018-07-06
  • 2016-01-22
  • 2020-03-26
  • 2019-01-26
  • 1970-01-01
相关资源
最近更新 更多