使用jpa api标准加入不相关的实体 [英] Join unrelated entities with jpa api criteria

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

问题描述

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

Two database tables have a foreign key relationship.

它们映射到两个实体 A B 通过JPA,但是连接列是从实体中手动删除的,因此在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.

使用条件api是否可以创建一个连接两个表的查询?

Using criteria api is it possible to to create a query which joins the two tables ?

我在互联网上找到的所有示例都使用连接列来实现目标,但是,如上所述,它已从代码中删除,因为大多数时候我对 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.

无论如何,要创建一个使用多个不相关实体的查询,你需要将它们作为 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 api标准加入不相关的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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