Search code examples
javaspring-datahql

Throwing Exception for UPDATE query if WHERE get empty result


Inside the controller layer, I get two parameters id of Strategy entity and new status for the update.

@PostMapping("/{id}/status/update")
public ResponseEntity<Long> updateStatus(@PathVariable(name = "id") Long id,
                                         @NotNull @RequestBody Map<String, String> status) {

I need the validate id and if Strategy does not exist throw exception to the client.

Method in the repository:

@Modifying
@Query("UPDATE Strategy s SET s.status =:status WHERE s.id = :id")
void updateStatusById(@NotNull Long id, @NotNull String status);

Obvious the solution is to use findById(ID id) of JpaRepository but this gives addition query to the database. As a midterm solution, I can use a single transaction for two queries like this:

In StrategyService:

@Transactional
public void update(@NotNull Long id, @NotNull String status) {
    strategyRepository.findById(id).orElseThrow();
    updateStatusById(id, status);
}

This single transaction but still a couple of queries. Very important to hold the hight speed of this query due to it call extremely often. How I can throw Exception directly from updateStatusById without addition query? Maybe somehow modifying HQL query or use native SQL or add default implementation?


Solution

  • instead of

    void updateStatusById(@NotNull Long id, @NotNull String status);
    

    one could define the method as

    int updateStatusById(@NotNull Long id, @NotNull String status);
    

    In this case, the returned value is the number of updated entities/rows in the database. This is a JDBC feature and incorporated within Spring.

    Now, after the query has been executed (int updated = updateStatusById(id, status);), one can check how many entities were updated. If 0 elements were updated, an Exception can be thrown.