HQl equivalent of sql query
String SQL_QUERY = "SELECT count(*) FROM (SELECT * FROM Url as U where U.pageType=" + 1 + " group by U.pageId having count(U.pageId) = 1)";
query = session.createQuery(SQL_QUERY);
I am getting an error
org.hibernate.hql.ast.QueryS开发者_StackOverflowyntaxException: unexpected token: ( near line 1, column 23 [ SELECT count() FROM (SELECT * FROM Url as U where U.pageType = 2 group by U.pageId having count(U.pageId) = 1)]
You can use group by and having and subqueries in hql as well.
Some examples:
link text
Your query seems to be ok as HQL code. Pay attention to the Capital letters for the entities: for example url
in your bean class could be Url
.
Anyway there's the method createSQLQuery(queryString)
to run a query in SQL language.
In HQL you cannot use subqueries in FROM
clause.
In this particular case (with having count(U.pageId) = 1
) the same result should be produced by the following query (though I'm not sure about performance):
SELECT count(u) FROM Url u WHERE u.pageType = 2 AND
1 = (SELECT count(uu) FROM Url uu WHERE u.pageId = uu.pageId)
If it's not suitable, you can use session.createSQLQuery()
.
精彩评论