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

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

问题描述

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

Two database tables have a foreign key relationship.

它们被JPA映射到两个实体 A B ,但是联接列是从实体中手动删除的,因此在JPA世界类 A B 不相关,并且您不能通过字段/属性从一个导航到另一个.

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天全站免登陆