Update Query and return a single column

Viewed 56

I have following custom Query:

    @Transactional
    @Modifying
    @Query(value = "UPDATE ARTICLE set likes = likes + 1 WHERE article_id = ?1", nativeQuery = true)
    int likeArticleById(UUID uuid);

So this Method returns me the number of changed rows.

Is there any possiblity to get the updated value as return value?

In this example I am updating the number of likes and want back the updated number of likes.

1 Answers

What you can do is to wrap in another @Transactional method the update and retrieve likes operation. The code should look like this:

This method should be in a @Service class:

@Transactional
int likeArticleAndRetriveNewLikes(UUID uuid) {
    repository.likeArticleById(uuid);
    return repository.getArticleLikesById(uuid);
}

These are the exposed methods from your @Repository:

@Modifying
@Query(value = "UPDATE ARTICLE set likes = likes + 1 WHERE article_id = ?1", nativeQuery = true)
int likeArticleById(UUID uuid);

@Query(value = "SELECT likes FROM ARTICLE WHERE article_id = ?1", nativeQuery = true)
int getArticleLikesById(UUID uuid);
Related