-->

How to get count of updated records in spring data

2019-04-29 05:08发布

问题:

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?

回答1:

If you take a look at ModifyingExecutor, which is used to execute this query

@Override
protected Object doExecute(AbstractJpaQuery query, Object[] values) {
    int result = query.createQuery(values).executeUpdate();
    if (em != null) {
        em.clear();
    }
    return result;
}

Then you see, it only delegates to native JPA infrastructure, to return number of updated elements.

So, this might have to do with used database or ORM framework configuration, other than that, the query you wrote should return correct result.