Hibernate Criteria Subquery(休眠条件子查询)
问题描述
我需要使用 detachedCriteria 执行此 SQL 查询:
I need to do this SQL query with detachedCriteria:
SELECT g.id FROM games g
WHERE NOT EXISTS (
SELECT 1 FROM users_games ug WHERE ug.user_id = 1 AND g.id = ug.game_id)
我们的想法是从不属于用户的游戏中获取 ID.我用 detachedCriteria 尝试了 10 种不同的方法,但我得到了未知实体:null"MappingException代码应如下所示:
The idea is to get the ids from the games that aren't owned by the user. I tried like 10 different approaches with detachedCriteria but I get the "Unknown entity: null" MappingException The code should look like:
DetachedCriteria subquery = DetachedCriteria.forClass(UserGame.class, "ug")
.add(Restrictions.eq("ug.user.id", 1))
.add(Restrictions.eqProperty("ug.game.id","u.id"));
DetachedCriteria criteria = DetachedCriteria.forClass(Game.class, "g")
.add(Subqueries.notExists(subquery));
还将预测设置为仅返回游戏的 id.
Setting also the projections to return only the id of the games.
有什么想法吗?我认为 Hibernate 在加入没有别名的查询时遇到了一些麻烦.添加别名有效,但结果非常错误.
Any ideas? I think Hibernate has some trouble joining the queries with no alias. Adding alias works but the results are quite wrong.
推荐答案
需要添加别名,如下:
DetachedCriteria subquery = DetachedCriteria.forClass(UserGame.class, "ug")
.addAlias("ug.user", "user")
.add(Restrictions.eq("user.id", 1))
.addAlias("ug.game", "game")
.add(Restrictions.eqProperty("game.id","u.id"));
应该有帮助
这篇关于休眠条件子查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:休眠条件子查询
基础教程推荐
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
