Java 如何在 Hibernate 中设置内部查询的限制?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2738880/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 12:18:47  来源:igfitidea点击:

How to set a limit to inner query in Hibernate?

javamysqlhibernatehql

提问by serg

I have HQL like this:

我有这样的 HQL:

from Table1 t1 where t1.name not in (select t2.name from Table2 t2 order by t2.date limit 10)

The problem is it doesn't understand limitkeyword. Is there a way to run such query without splitting it into two subqueries?

问题是它不理解limit关键字。有没有办法在不将其拆分为两个子查询的情况下运行此类查询?

采纳答案by Thierry

look at How do you do a limit query in HQL?

看看你如何在 HQL 中进行限制查询?

you can't limit a query written in hql with hql. You need to make a call to setMaxResults on the Query object, which i guess will prevent you from applying a limit on a hql subquery.

你不能用 hql 限制用 hql 编写的查询。您需要在 Query 对象上调用 setMaxResults ,我想这会阻止您对 hql 子查询应用限制。

This leave you with the option of

这让您可以选择

  • writting it as a sql-query or
  • trying to find another way to write your hql query so that you don't need a limit in a subquery.
  • 将其写为 sql-query 或
  • 试图找到另一种编写 hql 查询的方法,以便您不需要在子查询中进行限制。

回答by flyinaway

If you submit the query as an SQLQuery and then add your class as an entity, you can use limit, as the query is submittet as sql. You have to use sql Syntax though.

如果您将查询作为 SQLQuery 提交,然后将您的类添加为实体,则可以使用限制,因为查询是作为 sql 提交的。不过,您必须使用 sql 语法。

String sql = "select * from Supplier limit 1";
SQLQuery query = session.createSQLQuery(sql);
query.addEntity(Supplier.class);
List results = query.list();

--> (also working with subselects)

-->(也使用子选择)