Is it possible with JPA using play framework to execute an UPDATE sql query?
For the moment what I do to make an update to an entity is:
- To retrieve the entity via the find() method or a select query in the find() method
- Change the value I want
- call the save() method on the object
But I guess it makes 2 queries: a SELECT and an UPDATE.
Is there a way to do everything using only one query? Only an UPDATE query?
Thank you for your help
As long as you're using the API methods, I don't think you'll get around your 2-queries problem. The entity manager can't just start updating entities. It has to find them first, check their state and then decide if an update is really necessary, i.e. if changes were made or not.
You could however, always write your own parametrized update statement using
JPQL
. Yourfind()
will most likely use an id or something similar, which matches the primary key of your entity.You could just pass the id into the statement and update directly. I would only do this however, if the id isn't coming from user input but rather from a previous select. In other words, guaranteed to be an existing entity and the one you really want.
The query could look something like this:
Where you pass in newValue and id as a parameter.
However, I would rather let the entity manager do all the work. Why do you want to do it in a single statement anyway? Unless you're doing a ton of the operations, speed shouldn't be a problem as these short and specific statements are usually quite fast.