如何使用 JPA Criteria API 加入不相关的实体 [英] How to join unrelated entities with the JPA Criteria API

查看:34
本文介绍了如何使用 JPA Criteria API 加入不相关的实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

两个数据库表有外键关系.

Two database tables have a foreign key relationship.

它们被JPA映射到两个实体AB,但是连接列是从实体中手动删除的,所以在JPA世界类AB 不相关,您无法通过字段/属性从一个导航到另一个.

They are mapped to two entities A and B by JPA, but the join columns are manually removed from the entities, so in JPA world classes A and B are not related and you cannot navigate from one to the other through a field/property.

使用 JPA Criteria API,是否可以创建连接两个表的查询?

Using the JPA Criteria API, is it possible to create a query which joins the two tables?

我在互联网上找到的所有示例都使用 join 列来实现目标,但是,如上所述,它已从代码中删除,因为大多数时候我对 A 之间的关系不感兴趣和B,我担心可能的开销.

All examples I found on internet uses the join column to achieve the goal, but, as stated above, it was removed from the code because most time I'm not interested in the relationship between A and B and I'm afraid about possible overhead.

推荐答案

第一:外键关系不仅仅用于导航.它们主要用于确保不会在关系中引入虚假值.它们还可以帮助数据库进行查询优化.我建议你重新考虑一下.

First: Foreign key relationship are not only for navigating. They mainly serve to ensure that no spurious values are introduced in the relationship. They also may help the database for query optimization. I would advise you to reconsider that.

无论如何,要创建使用多个不相关实体的查询,您需要将它们作为 from (root) 实体(就像在 SQL 或 JPQL 中所做的那样)

Anyway, for creating a query that uses several unrelated entities, you need to put them as from (root) entities (as you would do in SQL or JPQL)

SELECT .... FROM Link l, Training t WHERE l.attribute = t.attribute;

Root<Link> rootLink = criteriaQuery.from(Link.class);
Root<Training> rootTraining = criteriaQuery.from(Training.class);
...
criteriaQuery.where(
    criteriaBuilder.equal(rootLink.get(link_.linkAttribute), trainingLink));

这篇关于如何使用 JPA Criteria API 加入不相关的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆