简体   繁体   English

如何限制JPQL查询中更新的行数?

[英]How can I limit the number of rows updated in a JPQL query?

I want to limit this update query to only update 5 rows: 我想将此更新查询限制为仅更新5行:

Query updateQuery = em.createQuery("update Entity e SET e.myVar = 1");
updateQuery.setMaxResults(5).executeUpdate();

setMaxResults does not seem to do the job. setMaxResults似乎没有完成这项工作。 How can I do this in jpql? 我怎么能在jpql中这样做?

If portability is not a issue, then you can go for database specific native query. 如果可移植性不是问题,那么您可以进行特定于数据库的本机查询。

  • Oracle : em.createNativeQuery("update TableName SET myVar = 1 where id IN (SELECT id FROM TableName WHERE ROWNUM <= 5)").executeUpdate(); Oracle: em.createNativeQuery("update TableName SET myVar = 1 where id IN (SELECT id FROM TableName WHERE ROWNUM <= 5)").executeUpdate();

  • MySql : em.createNativeQuery("update TableName SET myVar = 1 where id IN (SELECT id FROM TableName LIMIT 5)").executeUpdate(); MySql: em.createNativeQuery("update TableName SET myVar = 1 where id IN (SELECT id FROM TableName LIMIT 5)").executeUpdate();

ROWNUM & LIMIT are used to limit number of results in a query for Oracle & MySql respectively. ROWNUMLIMIT分别用于限制Oracle和MySql查询中的结果数。

Haven't mentioned which database you are using. 没有提到您正在使用哪个数据库。 Provided sample-code might help you, make alterations accordingly. 提供的示例代码可能会帮助您,相应地进行更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM