Fabien Henon
Fabien Henon

Reputation: 823

Update query instead of select + save

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:

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

Upvotes: 0

Views: 1046

Answers (1)

Sebastian_H
Sebastian_H

Reputation: 349

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. Your find() 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:

UPDATE MyTable SET MyValue = :newValue WHERE MyId = :id 

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.

Upvotes: 2

Related Questions