怎么写的秩序和限制查询在JPA
问题描述:
我希望根据提交我的表中的“MasterScrip” totalTradedVolume“来获取前10个结果 当我写下面的查询:
Collection<MasterScrip> sm=null;
sm=em.createQuery("select m from MasterScrip m where m.type = :type order by m.totalTradedVolume limit 2").setParameter("type", type).getResultList();
我得到以下exc eption:
Caused by: java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager:
Exception Description: Syntax error parsing the query [select m from MasterScrip m where m.type = :type order by m.totalTradedVolume limit 2], line 1, column 78: unexpected token [limit].
Internal Exception: NoViableAltException([email protected][])
我的jpa查询出错了。任何人都可以改正我吗?
答
limit
在JPA中无法识别。您可以改用query.setMaxResults
方法:
sm = em.createQuery("select m from MasterScrip m where m.type = :type
order by m.totalTradedVolume")
.setParameter("type", type)
.setMaxResults(2).getResultList()
+4
为什么“限制”这个词不起作用? –
+6
@KorayTugay,我知道回答你的问题为时已晚,但为了让其他人受益,'limit'特定于某些数据库(mysql),但“HQL”旨在与所有支持Hibernate的数据库一起工作。 –
答
你可以解决它与Query setFirstResult and setMaxResult
方法
检查我asnwer到类似的问题http://*.com/questions/6708085/select-top-1 -result-using-jpa/6708151#6708151 – Jorge
这不是真的重复。类似的问题检索任意结果,这个问题是关于获得m.totalTradedVolume的最高值的结果。 –