简体   繁体   English

将 SQL 查询实现为 JPA 两个多对一关系的标准

[英]Implementing SQL query as JPA Criteria for two Many-To-One relationships

I am trying to build JPA criteria for the following scenario.我正在尝试为以下场景构建 JPA 标准。 I have the following 3 Entity classes, two of which have a @ManyToOne relationship to UniqueType, but UniqueType does not have an explicit relationship to any other class: The structure is as follows:我有以下 3 个 Entity 类,其中两个与 UniqueType 有@ManyToOne 关系,但 UniqueType 与任何其他 class 没有显式关系:结构如下:

-------------           -----------            ------------ 
   event         N:1    unique_type     1:N       detail
-------------           -----------            ------------
event_id (PK)           type_code (PK)         detail_id (PK)
type_code (FK)                                 type_code (FK)
                                               abbreviation

The SQL query that successfully selects the Event records filtered by the abbreviation:成功选择通过缩写过滤的事件记录的 SQL 查询:

SELECT
  event.event_id,
  event.type_code,
  detail.abbreviation
FROM
  event 
  JOIN unique_type ON event.type_code = unique_type.type_code
  JOIN detail ON detail.type_code = unique_type.type_code
WHERE detail.abbreviation = 'ABC'

I have the Event class as my root, but when I join to the UniqueType class, I am stuck because there is no explicit relationship to Detail on UniqueType我有事件 class 作为我的根,但是当我加入 UniqueType class 时,我被卡住了,因为与 UniqueType 上的详细信息没有明确的关系

Join<Event, UniqueType> joinToUniqueType = root.join(Event_.typeCode);
Join<UniqueType, ???>

I want to be able to search on abbreviation something like:我希望能够搜索类似的缩写:

predicates.add(builder.lower(joinToDetail.get(Detail_.abbreviation)),'ABC');

How can I write the criteria?我怎样才能写出标准? Any help is much appreciated.任何帮助深表感谢。

Since you want inner join semantics, you can use cross joins instead which the database will optimize away anyway.由于您需要内部联接语义,因此您可以使用交叉联接来代替,数据库无论如何都会对其进行优化。 Use the following使用以下

Root<Detail> event = query.from(Event.class);
Root<Detail> detail = query.from(Detail.class);

predicates.add(builder.eq(detail.get(Detail_.typeCode), event.get(Event_.typeCode));
predicates.add(builder.lower(detail.get(Detail_.abbreviation)),'ABC');

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

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