如何用Spring JPA/Hibernate Criteria Builder实现临时表关联查询
基于Hibernate Criteria Builder实现指定多表关联查询的方案
前置场景说明
本次查询共涉及3个对应数据库表的实体类,各实体的属性结构如下:
MainEntity:包含属性entityID、entityName、entityTypeEntityA:包含属性entityID、entityName、typeIdEntityB:包含属性typeId、entityType
原需求对应的原生SQL逻辑为:先对EntityA和EntityB做左连接生成临时结果集,再将MainEntity与该临时结果集做内连接,匹配双方的entityID、entityName字段,最终返回所有符合条件的MainEntity全字段数据。
注:原提供的原生SQL存在几处书写错误,需先修正才能正常运行:
- 子查询字段列表中
A.entityName和B.entityType之间遗漏逗号- 表别名拼写错误:
mainEnity多写字符、enityID少写字符- 关联条件引用了不存在的字段:
MainEntity无typeId属性、临时结果集无typeId字段,实际关联逻辑应为匹配双方的entityType字段
修正后可正常执行的等效原生SQL为:SELECT mainEntity.* FROM MainEntity mainEntity INNER JOIN ( SELECT A.entityID, A.entityName, B.entityType FROM EntityA A LEFT JOIN EntityB B ON A.typeId = B.typeId ) Temp ON mainEntity.entityID = Temp.entityID AND mainEntity.entityName = Temp.entityName AND mainEntity.entityType = Temp.entityType
Hibernate Criteria Builder实现逻辑
实现思路
通过Criteria API的子查询能力模拟原SQL中的派生临时表,无需直接编写原生SQL:
- 子查询对应原SQL中
EntityA左连接EntityB的逻辑,投影选取entityID、entityName、entityType三个字段作为临时结果集 - 主查询以
MainEntity为根表,将上述子查询结果作为内连接的关联对象,配置与原SQL一致的字段匹配条件
参考实现代码
// 获取Hibernate CriteriaBuilder实例 CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery<MainEntity> mainQuery = cb.createQuery(MainEntity.class); // 定义主查询的根表:MainEntity Root<MainEntity> mainRoot = mainQuery.from(MainEntity.class); // 定义子查询:对应EntityA left join EntityB的临时结果集 // TempProjection为接收投影结果的DTO类,包含与投影字段匹配的构造方法 Subquery<TempProjection> subQuery = mainQuery.subquery(TempProjection.class); Root<EntityA> aRoot = subQuery.from(EntityA.class); // 配置EntityA与EntityB的左连接,匹配typeId外键 Join<EntityA, EntityB> bJoin = aRoot.join("typeId", JoinType.LEFT); // 配置子查询的投影字段 subQuery.select(cb.construct( TempProjection.class, aRoot.get("entityID"), aRoot.get("entityName"), bJoin.get("entityType") )); // 配置主查询的内连接关联条件 mainQuery.select(mainRoot) .innerJoin(subQuery, joinOn -> cb.and( cb.equal(mainRoot.get("entityID"), joinOn.get("entityID")), cb.equal(mainRoot.get("entityName"), joinOn.get("entityName")), cb.equal(mainRoot.get("entityType"), joinOn.get("entityType")) ) ); // 执行查询获取结果 List<MainEntity> resultList = entityManager.createQuery(mainQuery).getResultList();
实现注意事项
- 代码中的
TempProjection仅用于承接子查询的投影结果,需要包含与投影字段一一对应的全参构造方法,不需要实现业务逻辑 - 如果实体类已经通过JPA注解定义了外键关联关系(比如
EntityA的typeId属性标注了@ManyToOne关联EntityB),可以直接使用关联属性名构建Join条件,不需要手动匹配外键字段 - 如果原业务逻辑中确实存在跨字段匹配的特殊规则,只需要在连接条件的
cb.and()中添加对应的equal判断即可,无需调整整体查询结构
内容的提问来源于stack exchange,提问作者kshashi
相关产品推荐
相关产品推荐

