我声明我在Mac OSX上使用Hibernate,MySQL。
我看了关注我的问题的帖子,但不幸的是我无法解决它。下面是有问题的代码:
public List<FeedMessage> getLatestFeedMessage() {
List<FeedMessage> messages = new ArrayList<>();
String hql = "from (select nomeFeed, title, max(pubDate) as maxdate "
+ "from FeedMessage group by nomeFeed) as x inner join FeedMessage as f "
+ "on f.nomeFeed = x.nomeFeed and f.pubDate = x.maxdate";
System.out.println(hql);
try {
session = HibernateUtil.getSessionFactory().openSession();
Query query = session.createQuery(hql);
messages=query.list();
} catch (QueryException e) {
e.printStackTrace();
} finally {
if(session.isOpen())
session.close();
}
return messages;
}
我试图从MySQL数据库中选择每个组的第一行,但是我收到以下错误:
org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ( near line 1, column 6 [from (select nomeFeed, title, max(pubDate) as maxdate from it.unirc.fantapjam.FeedMessage.Model.FeedMessage group by nomeFeed) as x inner join FeedMessage as f on f.nomeFeed = x.nomeFeed and f.pubDate = x.maxdate]
at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:91)
at org.hibernate.hql.internal.ast.ErrorCounter.throwQueryException(ErrorCounter.java:109)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:304)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:203)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:158)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:126)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:88)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:190)
at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:301)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:236)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1796)...........
我认为问题是Hibernate无法翻译查询,因为如果我直接运行到MySQL,这是有效的。或者,我尝试运行后续查询:
String hql = "from (select nomeFeed, title, max(pubDate) as maxdate "
+ "from FeedMessage "
+ "group by nomeFeed) as x, FeedMessage as f "
+ "where f.nomeFeed = x.nomeFeed and f.pubDate = x.maxdate";
但我得到的结果相同。
答案 0 :(得分:1)
不幸的是你不能在HQL中这样做。根据hibernate文档https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html#queryhql-subqueries
请注意,HQL子查询只能在select或where中出现 条款。
而您的子查询位于 from 子句中。如果您希望在from语句中使用子查询,则必须使用本文所述的本机SQL:https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querysql.html