简体   繁体   English

使用 JPA 标准 API 的 JOIN 查询中的反向类型

[英]Reverse types in JOIN query with JPA Criteria API

I would like to return a list of Group objects using a JPA criteria query.我想使用 JPA 条件查询返回一个Group对象列表。 A group can either be empty or contain participants .一个组可以是空的,也可以包含参与者 Each Participant has a reference to its Group .每个Participant都有一个对其Group的引用。 The group knows nothing about the participants.该小组对参与者一无所知。 Now I would like to implement a criteria query to dynamically return either:现在我想实现一个标准查询来动态返回:

  1. Only groups with participants.只有参与者的团体。
  2. All groups (including empty ones).所有组(包括空组)。

Basically, this is my Group class:基本上,这是我的Group class:

public class Group {
  private long id;
}

And this is my Participant :这是我的Participant

public class Participant {
  @ManyToOne
  @JoinColumn(name = "FK_GROUP")
  private Group group;
}

I left out all properties, methods and annotations for sake of simplicity.为了简单起见,我省略了所有属性、方法和注释。

This will return both, empty groups and groups with participants, in plain SQL:这将返回空组和有参与者的组,简单来说就是 SQL:

SELECT DISTINCT G.* FROM GROUP_TABLE G
  LEFT JOIN PARTICIPANT_TABLE P ON P.FK_GROUP=G.ID;

Now I'd like to do the same thing with Criteria API:现在我想对标准 API 做同样的事情:

if (includeEmptyGroups) {
  // ...
  Root<Group> root = criteria.from(Group.class);
  Join<Participant, Group> join = root.join("id"); <-- This is my issue!
  criteria.select(root).distinct(true);
  //...
}
else {
  // ...
}

The query should return a list of Group objects, so I chose that type for my Root object and the from() method.查询应返回Group对象的列表,因此我为我的Root object 和from()方法选择了该类型。 Now, most tutorials would define a Join<Group, Participant> , and join participants by a property of the Group class.现在,大多数教程会定义一个Join<Group, Participant> ,并通过Group class 的属性加入参与者。

Due to my reversed class structure, however, I cannot do this.但是,由于我的反向class 结构,我不能这样做。 The code above does not work, because I reversed the types and JPA cannot join by simple types.上面的代码不起作用,因为我颠倒了类型,JPA 不能通过简单类型加入。 I'm unsure, if I approach the problem correctly at all.我不确定我是否完全正确地解决了这个问题。

I could switch types around and base my Root on the Participant class, then join with Group .我可以切换类型并将我的Root基于Participant class,然后加入Group This, however, makes it impossible to conditionally return empty groups.但是,这使得无法有条件地返回空组。 Is it even possible to build the plain SQL query with Criteria API?甚至可以使用条件 API 构建普通的 SQL 查询吗?

Since the JPA contracts do not allow for left joining entities, you can only use HQL or a query builder API on top of HQL like eg Blaze-Persistence which supports this.由于 JPA 合同不允许左连接实体,您只能在 HQL 之上使用 HQL 或查询构建器 API,例如支持此 功能的 Blaze-Persistence Either way, you will need at least Hibernate 5.1 which is the first version that added support for entity joins.无论哪种方式,您至少需要 Hibernate 5.1,这是第一个添加实体连接支持的版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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