java - 使用 JPA Criteria,如何在不获取连接实体的情况下获取连接实体的子实体?

标签 java hibernate jpa criteria criteria-api

在我的项目中,我使用 Groovy 和 Spring Data JPA 的规范来构建 Hibernate 查询。

我无法提供我的实际查询,但为了说明我的问题,假设我有建筑实体,每个建筑都有楼层,每个楼层都有房间和 window 。

我尝试模拟的行为类似于此 native SQL 查询:

SELECT b.*, r.*
FROM building b
INNER JOIN floor f ON b.id = f.building_id
INNER JOIN window w ON f.id = w.floor_id
LEFT OUTER JOIN room r ON f.id = r.floor_id
WHERE w.id = 1;

我有一个类似于以下的规范:

public class MySpec implements Specification<Building> {
    @Override
    public Predicate toPredicate(final Root<Building> root, final CriteriaQuery<?> query, final CriteriaBuilder cb) {
        final Join floorsJoin = root.join("floors");
        final Join windowsJoin = floorsJoin.join("windows");

        //I'd like to remove this line
        final Fetch floorsFetch = root.fetch("floors"); // <---

        floorsFetch.fetch("rooms", JoinType.LEFT);

        cb.equal(windowsJoin.get("id"), 1L);
    }
}

上面注释的行是我的问题。如果我保留它,生成的查询看起来像这样:

SELECT b.*, f2.*, r.*
FROM building b
INNER JOIN floor f ON b.id = f.building_id
INNER JOIN window w ON f.id = w.floor_id
INNER JOIN floor f2 ON b.id = f2.building_id
LEFT OUTER JOIN room r ON f2.id = r.floor_id
WHERE w.id = 1;

(请注意 floor 的重复 INNER JOIN 以及不需要的 f2.* 数据)

如果我删除它,并使用 floorsJoin 来获取房间,我会收到以下 Hibernate 错误:

org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list

不需要的 f2.* 数据没问题,但我无法将上面的 floorsJoin 替换为 floorsFetch 因为我需要加入使用 windows 表(不获取 windows)并且 Fetch 类没有 .join 方法。

我很难弄清楚如何在生成单个查询的同时完成我需要的任务;当然我一定错过了一些简单的东西。

如果您能提供任何想法或建议,我们将不胜感激。

非常感谢, B.J.

最佳答案

JPA Criteria API 并不是那么简单。使用 Hibernate,您可以简单地将 Fetch 转换为 Join 我猜但这对您没有多大帮助。我不确定在这种情况下如何使用该规范,但如果您可以将查询作为一个整体编写,它可能如下所示

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Tuple> cq = cb.createTupleQuery();

Root<Building> root = cq.from(Building.class);
final Join floorsJoin = root.join("floors");
final Join windowsJoin = floorsJoin.join("windows");
final Join roomsJoin = floorsJoin.join("rooms", JoinType.LEFT);

cb.equal(windowsJoin.get("id"), 1L);

cq.multiselect(
    root,
    roomsJoin
);

关于java - 使用 JPA Criteria,如何在不获取连接实体的情况下获取连接实体的子实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40686351/

相关文章:

java - 找不到适合“jdbc :mysql://localhost:3306/mysql”的驱动程序

java - 插入现有行/选择非空字段

java - Hibernate 或 Java 中是否有类似于 PHP $_SESSION 的 Session 变量

mysql - 查询以在 HQL 中获取超过 6500 条记录

mysql - com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException : Unknown column '____' in 'field list'

java - 如何将图像放入 GoogleMaps api fragment 中

java - 有关数据库池和 connection.setReadOnly() 方法的行为

java - 查询没有返回唯一结果: 3; nested exception is javax. persistence.NonUniqueResultException:(Spring JPA项目)

tomcat - 尝试使用 JPA 从数据库读取数据时出现 java.lang.NullPointerException

java - 为什么 Java swing 组件显示为不轻量级,尽管它们应该是轻量级的?