java - JPQL内连接查询

标签 java hibernate jpa jpql

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

订单_

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

我正在尝试获取 List<QRequest>来自Listorder_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 查询。

最佳答案

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

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

关于java - JPQL内连接查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49977250/

相关文章:

java - org.apache.openejb.server.cxf.rs.PojoInvoker 抛出 invokingTargetException

java - 数据库序列如何管理竞争条件?

java - Hibernate/JPA 将 native 查询的结果映射到持有实体的非实体

java - 访问用户上的 LAZY 集合时出现 LazyInitializationException

java - 使用 @OneToMany 或 @ManyToMany 定位未映射的类(多数据库连接)

java split string with scanner 不丢失定界符

java - 查找最相似的 List<String> 的有效方法

java - 用 cucumber 等待,不要关闭浏览器

java - Hibernate 在插入/更新 blob 时使用两倍文件大小的查询

java - 关系 OneToOne 的 PSQLException : relation "car_model" does not exist