Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get count of updated records in spring data jpa?

Tags:

People also ask

How does JPA get count of records?

count() repository method If you want to know the total number of rows available in the entity table, use the count derived method of the CrudRepository interface. For example, the following getCustomerCount method retrieves the number of entities available in the table using the method count.

What is @query used for spring data?

Spring Data JPA @Query The @Query annotation declares finder queries directly on repository methods. While similar @NamedQuery is used on domain classes, Spring Data JPA @Query annotation is used on Repository interface. This frees the domain classes from persistence specific information, which is a good thing.

How do I update JPA Spring Data?

Because of that, you need to tell Spring Data JPA that you provided a modifying statement as the value of the @Query annotation. You can do that by annotating your repository method with a @Modifying annotation. Spring Data JPA then provides the required code to execute your INSERT, UPDATE or DELETE statement.


I am using spring data jpa with hibernate as jpa persistence provider.

I am using native queries in my application. There are some update queries and I would like to get the actual number of records updated when the update query gets executed. Is there a way in spring data jpa to do this?

I am currently following the below approach;

@Modifying
@Query(value="update table x set x_provision = ?1 where x_id = ?2", nativeQuery=true)
int updateProvision(Integer provision, Integer id);

@Transactional is added on service layer.

The problem here is that when the table gets updated I get the count as 1. But there are some cases where no rows are updated. In this case also I get the count as 1. But I would like to receive the actual number of records updated which sometimes is 0.

Can someone let me know if I am doing something wrong here?