Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

jpql

I want to limit this update query to only update 5 rows:

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

setMaxResults does not seem to do the job. How can I do this in jpql?

like image 891
Grant Cermak Avatar asked Oct 16 '25 15:10

Grant Cermak


1 Answers

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();

  • 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.

Haven't mentioned which database you are using. Provided sample-code might help you, make alterations accordingly.

like image 137
Nayan Wadekar Avatar answered Oct 18 '25 04:10

Nayan Wadekar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!